﻿
function _Context() {
    var errorMessage = "Context is not available.";
    if (typeof GetGlobalContext != "undefined")
    { return GetGlobalContext(); }
    else
    {
        if (typeof Xrm != "undefined") {
            return Xrm.Page.context;
        }
        else { return new Error(errorMessage); }
    }
};

function Buildmenu(areaTitle, area, siteMapDoc) {

    var context = _Context();
    var menuitem = '<li class="has-popup static" role="menuitem" aria-haspopup="Menu1:submenu:2" style="float: left; position: relative;">';
    menuitem += '<a tabindex="-1" class="popout level1 level1 static" href="#">' + areaTitle + '</a>';
    menuitem += SubMenuStart();

    // Iterate through groups
    var groups = siteMapDoc.selectNodes("//SiteMap/Area[@Id='" + area + "']/Group");
    var groupCount = groups.length;

    for (var g = 0; g < groupCount; g++) {
        var group = groups[g].getAttribute("Id");
        var groupTitle = "";


        // If title wasn't found in resource xml get it from sitemap
        if (groupTitle == "") {
            var groupTitleTmp = siteMapDoc.selectSingleNode("//SiteMap/Area[@Id='" + area + "']/Group[@Id='" + group + "']/Titles/Title[@LCID='" + context.getOrgLcid() + "']/@Title");
            if (groupTitleTmp != null)
                groupTitle = groupTitleTmp.nodeValue;
            else
                groupTitle = group;

        }

        var subAreas = siteMapDoc.selectNodes("//SiteMap/Area[@Id='" + area + "']/Group[@Id='" + group + "']/SubArea");

        var subAreaCount = subAreas.length;

        for (var s = 0; s < subAreaCount; s++) {
            var subArea = subAreas[s].getAttribute("Id");
            var subAreaTitle = GetSystemSubAreaNames(subArea);

            // If title wasn't found in resource xml get it from sitemap
            if (subAreaTitle == "") {
                var subAreaTitleTmp = siteMapDoc.selectSingleNode("//SiteMap/Area[@Id='" + area + "']/Group[@Id='" + group + "']/SubArea[@Id='" + subArea + "']/Titles/Title[@LCID='" + context.getOrgLcid() + "']/@Title");
                if (subAreaTitleTmp != null)
                    subAreaTitle = subAreaTitleTmp.nodeValue;
                else {
                    subAreaTitleTmp = siteMapDoc.selectSingleNode("//SiteMap/Area[@Id='" + area + "']/Group[@Id='" + group + "']/SubArea[@Id='" + subArea + "']/@Title");
                    if (subAreaTitleTmp != null)
                        subAreaTitle = subAreaTitleTmp.nodeValue;
                }
            }

            var entityLogicalName = subAreas[s].getAttribute("Entity");

            if ((subAreaTitle != null && subAreaTitle != "") || (entityLogicalName != null && entityLogicalName != "")) {

                var url = subAreas[s].getAttribute("Url");
                if (url == null) {
                    url = "/_root/homepage.aspx?etc=&sitemappath=" + encodeURIComponent(area + "|" + group + "|" + subArea);
                }
                else {
                    if (url.indexOf("?") == -1)
                        url += "?sitemappath=" + encodeURIComponent(area + "|" + group + "|" + subArea);
                    else
                        url += "&sitemappath=" + encodeURIComponent(area + "|" + group + "|" + subArea);
                }

                var title = subAreas[s].getAttribute("Title");

                if (entityLogicalName != null && entityLogicalName != "") {
                    ValidateUserPrivilegeToEntity(entityLogicalName, area + subArea);
                }
                else {
                    var needCheckPr = false;
                    var priviledgeTags = siteMapDoc.selectNodes("//SiteMap/Area[@Id='" + area + "']/Group[@Id='" + group + "']/SubArea[@Id='" + subArea + "']/Privilege");

                    for (var sss2 = 0; sss2 < priviledgeTags.length; sss2++) {
                        var aPriviledgeTagEntity = priviledgeTags[sss2].getAttribute("Entity");

                        if (aPriviledgeTagEntity != null && aPriviledgeTagEntity != "") {
                            needCheckPr = true;
                            ValidateUserPrivilegeToEntity(aPriviledgeTagEntity, area + subArea);
                        }
                    }
                    if (!needCheckPr && subArea == "nav_apptbook") {
                        ValidateUserPrivilegeToEntity('calendar', area + subArea);
                    }
                    else if (!needCheckPr && subArea == "nav_datamanagement") {
                        ValidateUserPrivilegeToEntity('import', area + subArea);
                    }
                }
                if (entityLogicalName != null && entityLogicalName != "") {
                    var mdq = SDK.Metadata.Query;
                    var semp = mdq.SearchableAttributeMetadataProperties;
                    var emp = mdq.EntityMetadataProperties;
                    var entityProperties = new mdq.MetadataPropertiesExpression(false, [emp.LogicalName, emp.DisplayCollectionName, emp.IconLargeName, emp.IconMediumName, emp.IconSmallName, emp.ObjectTypeCode]);
                    // Define filter
                    var entityFilter = new mdq.MetadataFilterExpression(mdq.LogicalOperator.And);
                    entityFilter.addCondition(semp.LogicalName, mdq.MetadataConditionOperator.Equals, entityLogicalName);

                    // LabelQuery
                    var lq = new mdq.LabelQueryExpression([context.getOrgLcid()]);
                    var query = new mdq.EntityQueryExpression(entityFilter, entityProperties, null, null, lq);

                    // Retrieve the metadata and continues through other operations asynchronously 
                    // using the successCallback parameters containing the next steps.
                    GetMetadataChanges(
                        mdq,
                     query,
                     null, //No ClientVersionStamp passed the first time.
                     null, //No DeletedMetadataFilters are defined.
                    function (results, subArea) {

                        if (results != null && results.EntityMetadata != null && results.EntityMetadata.length > 0) {
                            var entityData = results.EntityMetadata[0];

                            var reallabel = entityData.DisplayCollectionName.UserLocalizedLabel.Label;
                            var realObjectTypeCode = entityData.ObjectTypeCode;

                            if (parent.$("#nmu" + area + subArea) != null) {
                                if (parent.$("#nmu" + area + subArea).attr("onclick") != null) {
                                    parent.$("#nmu" + area + subArea).attr("onclick", parent.$("#nmu" + area + subArea).attr("onclick").replace("etc=&", "etc=" + ((entityData.ObjectTypeCode != null) ? entityData.ObjectTypeCode : "") + "&"));
                                }
                                parent.$("#nmu" + area + subArea).text(reallabel);
                            }
                        }
                        else {
                            parent.$("#nmu" + area + subArea).css("visibility", "hidden");
                            parent.$("#nmu" + area + subArea).css("display", "none");
                        }

                    },
                        function (error) {

                        },
                        subArea
                    );

                }
                if (subAreaTitle == "") {
                    if (title == null) {
                        subAreaTitle = entityLogicalName;
                    }
                    else {
                        subAreaTitle = title;
                    }

                }

            }

            // Add the SiteMap subareas as Submenues
            if (entityLogicalName != null && entityLogicalName != "") {
                url = context.getClientUrl() + url;
            }
            menuitem += BuilSubMmenu(subAreaTitle, url, "nmu" + area + subArea);
        }
        if (g < groupCount - 1) {
            // After each group is finished add a separator
            menuitem += BuildSeparator();
        }
    }

    menuitem += SubMenuEnd();
    return menuitem;
}

function GetMetadataChanges(MDQuery, entityQueryExpression, clientVersionStamp, deletedMetadataFilter, successCallBack, errorCallback, passThroughObject) {

    var retrieveMetadataChangesRequest = new MDQuery.RetrieveMetadataChangesRequest(entityQueryExpression, clientVersionStamp, deletedMetadataFilter);

    MDQuery.RetrieveMetadataChanges(retrieveMetadataChangesRequest, successCallBack, errorCallback, passThroughObject);
}

function BuildSeparator() {
    var context = _Context();
    var separator = '<li class="dynamic" role="menuitem" style="position: relative;"><a tabindex="-1" href="#" ><img class="separator" alt="" src="' + context.getClientUrl() + '/WebResources/remcod_sep.png"></a></li>';
    return separator;
}

function BuilSubMmenu(text, url, id) {
    var submenuitem = '<li class="dynamic" role="menuitem" style="position: relative;"><a tabindex="-1" id="' + id + '" class="level2 level2 dynamic" href="';
    submenuitem += '#';
    submenuitem += '"';
    submenuitem += ' onclick="loadIframe(\'';
    submenuitem += url;
    submenuitem += '\')">';
    submenuitem += text + '</a></li>';
    return submenuitem;
}

function SubMenuStart() {
    var submenuitem = '<ul class="level2 dynamic" id="Menu1:submenu:2" style="left: 0px; top: 100%; display: none; position: absolute;">';
    return submenuitem;
}

function SubMenuEnd() {
    var submenuitem = " </ul></li>";
    return submenuitem;
}

function MenuStart() {
    var submenuitem = "<DIV id='Menu1' style='float: left; background-color: rgb( 0, 32, 80); border: none; color: White; font-variant: small-caps; font-family: \"Segoe UI\" , \"Segoe\" , Tahoma, Helvetica, Arial, sans-serif !important;'>";
    submenuitem += '<ul tabindex="0" class="level1 static" role="menubar" style="width: auto; float: left; position: relative;">';
    return submenuitem;
}

function MenuEnd(language) {
    var context = _Context();
    var submenuitem = "</ul>";
    var newAdvFindButton = "<span title='AdvanceFind' class='level1' id='onelcickAdvanceFindCus' style='margin-right: 275px; float: right;'><a  ";
    newAdvFindButton += " onclick='Mscrm.RibbonActions.openAdvancedFind()' href='javascript:;' style='color: white;' >";
    newAdvFindButton += '<img  alt="" src="' + context.getClientUrl() + '/WebResources/remcod_AdvFind.png">&nbsp;&nbsp;' + language["advancedFindTitle"] + '</a></span>';
    submenuitem += newAdvFindButton;
    submenuitem += "</div>";
    return submenuitem;
}

// Pages that contain BPF try to render menu 2 times. This counter is for preventing that to happen.
var BPFCounter = 1;
function AddNavigation(showButton) {
    setTimeout(function () {
        // Check if the menu was already rendered, and Do not show menu in old ribbon pages       
        if (parent.$("#Menu1").length == 0 && parent.$("#contentIFrame").length == 0 && BPFCounter == 1) {
            BPFCounter++;
            RetrieveUserPrivileges();
        }

    }, 2000);
    return showButton;
}

var oneClickEnglish = {
    "salesTitle": "Sales",
    "serviceTitle": "Service",
    "marketingTitle": "Marketing",
    "settingsTitle": "Settings",
    "helpTitle": "Help",
    "advancedFindTitle": "Advanced Find",
    "dashboardTitle": "Dashboards",
    "whatsNewTitle": "What's New",
    "activitiesTitle": "Activities",
    "queuesTitle": "Queues",
    "serviceCalendarTitle": "Service Calendar",
    "businessManagementTitle": "Business Management",
    "templatesTitle": "Templates",
    "productCatalogTitle": "Product Catalog",
    "administrationTitle": "Administration",
    "dataManagementTitle": "Data Management",
    "systemJobsTitle": "System Jobs",
    "documentManagementTitle": "Document Management",
    "auditingTitle": "Auditing",
    "customizationsTitle": "Customizations",
    "marketplaceTitle": "Marketplace",
    "emailConfigurationTitle": "Email Configuration",
    "alertsTitle": "Alerts",
    "calendarTitle": "Calendar",
    "highlightsTitle": "Highlights",
    "serviceManagementTitle": "Service Management",
    "knowledgeBaseTitle": "Knowledge Base",
    "customerCenterTitle": "Customer Center"
};
var oneClickSpanish = {
    "salesTitle": "Ventas",
    "serviceTitle": "Servicio",
    "marketingTitle": "Marketing", //sitemap item appears in english
    "settingsTitle": "Configuración",
    "helpTitle": "Ayuda",
    "advancedFindTitle": "Búsqueda avanzada",
    "dashboardTitle": "Paneles",
    "whatsNewTitle": "Novedades",
    "activitiesTitle": "Actividades",
    "queuesTitle": "Colas",
    "serviceCalendarTitle": "Calendario de Servicios",
    "businessManagementTitle": "Administración de Empresas",
    "templatesTitle": "Plantillas",
    "productCatalogTitle": "Catálogo de Productos",
    "administrationTitle": "Administración",
    "dataManagementTitle": "Administración de Datos",
    "systemJobsTitle": "Trabajos de Sistema",
    "documentManagementTitle": "Administración de Documentos",
    "auditingTitle": "Auditoría",
    "customizationsTitle": "Personalizaciones",
    "marketplaceTitle": "Marketplace",//sitemap item appears in english
    "emailConfigurationTitle": "Configuración de Correo Electrónico",
    "alertsTitle": "Alertas",
    "calendarTitle": "Calendario",
    "serviceManagementTitle": "Administración de Servicios",
    "knowledgeBaseTitle": "Base de Conocimientos",
    "customerCenterTitle": "Centro de Clientes"
};
var oneClickGerman = {
    "salesTitle": "Vertrieb",
    "serviceTitle": "Service",
    "marketingTitle": "Marketing",
    "settingsTitle": "Einstellungen",
    "helpTitle": "Hilfe",
    "advancedFindTitle": "Erweiterte Suche",
    "dashboardTitle": "Dashboards",
    "whatsNewTitle": "Neuigkeiten",
    "activitiesTitle": "Activities",
    "queuesTitle": "Warteschlangen",
    "serviceCalendarTitle": "Servicekalender",
    "businessManagementTitle": "Unternehmensmanagement",
    "templatesTitle": "Volagen",
    "productCatalogTitle": "Produktkatalog",
    "administrationTitle": "Verwaltung",
    "dataManagementTitle": "Datenverwaltung",
    "systemJobsTitle": "Systemaufräge",
    "documentManagementTitle": "Dokumentenverwaltung",
    "auditingTitle": "Überwachung",
    "customizationsTitle": "Anpassungen",
    "marketplaceTitle": "Marketplace",//sitemap item appears in english
    "emailConfigurationTitle": "E-mail-Konfiguration",
    "alertsTitle": "Warnungen",
    "calendarTitle": "Kalender",
    "serviceManagementTitle": "Servicemanagement",
    "knowledgeBaseTitle": "Knowledge Base",
    "customerCenterTitle": "Kundencenter"
};
var oneClickFrench = {
    "salesTitle": "Ventes",
    "serviceTitle": "Service",
    "marketingTitle": "Marketing",
    "settingsTitle": "Paramètres",
    "helpTitle": "Aide",
    "advancedFindTitle": "Recherche avancée",
    "dashboardTitle": "Tableaux de Bord",
    "whatsNewTitle": "Nouveautés",
    "activitiesTitle": "Activités",
    "queuesTitle": "Files d'attente",
    "serviceCalendarTitle": "Calendrier de Service",
    "businessManagementTitle": "Gestion D'Entreprise",
    "templatesTitle": "Modèles",
    "productCatalogTitle": "Catalogue de Produits",
    "administrationTitle": "Administration",
    "dataManagementTitle": "Gestion des Données",
    "systemJobsTitle": "Tâches Système",
    "documentManagementTitle": "Gestion des Documents",
    "auditingTitle": "Audit",
    "customizationsTitle": "Personnalisations",
    "marketplaceTitle": "Marketplace",//sitemap item appears in english
    "emailConfigurationTitle": "Configuration de la Messagerie",
    "alertsTitle": "Alertes",
    "calendarTitle": "Calendrier",
    "serviceManagementTitle": "Service Management",
    "knowledgeBaseTitle": "Knowledge Base",
    "customerCenterTitle": "Centre de clients"
};
var oneClickItalian = {
    "salesTitle": "Vendite",
    "serviceTitle": "Servizi",
    "marketingTitle": "Marketing",
    "settingsTitle": "Impostazioni",
    "helpTitle": "Guida",
    "advancedFindTitle": "Ricerca avanzata",
    "dashboardTitle": "Dashboard",
    "whatsNewTitle": "Novità",
    "activitiesTitle": "Impegni",
    "queuesTitle": "Code",
    "serviceCalendarTitle": "Calendario Servizi",
    "businessManagementTitle": "Gestione Aziendale",
    "templatesTitle": "Modelli",
    "productCatalogTitle": "Catalogo Prodotti",
    "administrationTitle": "Amministrazione",
    "dataManagementTitle": "Gestione Dati",
    "systemJobsTitle": "Processi di Sistema",
    "documentManagementTitle": "Gestione dei Documenti",
    "auditingTitle": "Controllo",
    "customizationsTitle": "Personalizzazioni",
    "marketplaceTitle": "Marketplace",//sitemap item appears in english
    "emailConfigurationTitle": "Configurazione E-Mail",
    "alertsTitle": "Avvisi",
    "calendarTitle": "Calendario",
    "serviceManagementTitle": "Service Management",
    "knowledgeBaseTitle": "Knowledge Base",
    "customerCenterTitle": "Centro clienti"
};
var oneClickPortuguesePortugal = {
    "salesTitle": "Vendas",
    "serviceTitle": "Serviço",
    "marketingTitle": "Marketing",
    "settingsTitle": "Definições",
    "helpTitle": "Ajuda",
    "advancedFindTitle": "Pesquisa Avançada",
    "dashboardTitle": "Dashboards",
    "whatsNewTitle": "Novidades",
    "activitiesTitle": "Atividades",
    "queuesTitle": "Filas",
    "serviceCalendarTitle": "Calendário de Serviços",
    "businessManagementTitle": "Gestão de Negócio",
    "templatesTitle": "Modelos",
    "productCatalogTitle": "Catálogo de Produtos",
    "administrationTitle": "Administração",
    "dataManagementTitle": "Gestão de Dados",
    "systemJobsTitle": "Tarefas de Sistema",
    "documentManagementTitle": "Gestão Documentos",
    "auditingTitle": "Auditoria",
    "customizationsTitle": "Personalizações",
    "marketplaceTitle": "Marketplace",//sitemap item appears in english
    "emailConfigurationTitle": "Configuração do Correio Eletrónico",
    "alertsTitle": "Alertas",
    "calendarTitle": "Calendário",
    "serviceManagementTitle": "Service Management",
    "knowledgeBaseTitle": "Knowledge Base",
    "customerCenterTitle": "Centro de Clientes"
};
var oneClickPortugueseBrazil = {
    "salesTitle": "Vendas",
    "serviceTitle": "Serviço",
    "marketingTitle": "Marketing",
    "settingsTitle": "Configurações",
    "helpTitle": "Ajuda",
    "advancedFindTitle": "Localização Avançada",
    "dashboardTitle": "Painéis",
    "whatsNewTitle": "Novidades",
    "activitiesTitle": "Atividades",
    "queuesTitle": "Filas",
    "serviceCalendarTitle": "Calendário de Serviços",
    "businessManagementTitle": "Gerenciamento de Negócios",
    "templatesTitle": "Modelos",
    "productCatalogTitle": "Catálogo de Produtos",
    "administrationTitle": "Administração",
    "dataManagementTitle": "Gerenciamento de Dados",
    "systemJobsTitle": "Trabalhos do Sistema",
    "documentManagementTitle": "Gerenciamento Documentos",
    "auditingTitle": "Auditoria",
    "customizationsTitle": "Personalizações",
    "marketplaceTitle": "Marketplace",//sitemap item appears in english
    "emailConfigurationTitle": "Configuração de Email",
    "alertsTitle": "Alertas",
    "calendarTitle": "Calendário",
    "serviceManagementTitle": "Service Management",
    "knowledgeBaseTitle": "Knowledge Base",
    "customerCenterTitle": "Central de Clientes"
};
var oneClickRussian = {
    "salesTitle": "Продажи",
    "serviceTitle": "Сервис",
    "marketingTitle": "Маркетинг",
    "settingsTitle": "Параметры",
    "helpTitle": "Справка",
    "advancedFindTitle": "Расширенный поиск",
    "dashboardTitle": "Панели мониторинга",
    "whatsNewTitle": "Что нового",
    "activitiesTitle": "Действия",
    "queuesTitle": "Очереди",
    "serviceCalendarTitle": "Календарь обслуживания",
    "businessManagementTitle": "Управление бизнесом",
    "templatesTitle": "Шаблоны",
    "productCatalogTitle": "Каталог продукции",
    "administrationTitle": "Администрирование",
    "dataManagementTitle": "Управление данными",
    "systemJobsTitle": "Системные задания",
    "documentManagementTitle": "Управление документами",
    "auditingTitle": "Аудит",
    "customizationsTitle": "Настройки",
    "marketplaceTitle": "Marketplace",//sitemap item appears in english
    "emailConfigurationTitle": "Настройка электронной почты",
    "alertsTitle": "Оповещения",
    "calendarTitle": "Календарь",
    "highlightsTitle": "Highlights",
    "serviceManagementTitle": "Service Management",
    "knowledgeBaseTitle": "Knowledge Base",
    "customerCenterTitle": "Центр клиентов"
};
var oneClickArabic = {
    "salesTitle": "المبيعات",
    "serviceTitle": "الخدمة",
    "marketingTitle": "التسويق",
    "settingsTitle": "إعدادات",
    "helpTitle": "تعليمات",
    "advancedFindTitle": "بحث متقدم",
    "dashboardTitle": "لوحات المعلومات",
    "whatsNewTitle": "الجديد",
    "activitiesTitle": "النشاط",
    "queuesTitle": "قوائم الانتظار",
    "serviceCalendarTitle": "تقويم الخدمة",
    "businessManagementTitle": "إدارة الأعمال",
    "templatesTitle": "القوالب",
    "productCatalogTitle": "كتالوج المنتجات",
    "administrationTitle": "الإدارة",
    "dataManagementTitle": "إدارة البيانات",
    "systemJobsTitle": "وظائف النظام",
    "documentManagementTitle": "إدارة المستندات",
    "auditingTitle": "تدقيق",
    "customizationsTitle": "تخصيصات",
    "marketplaceTitle": "Marketplace",//sitemap item appears in english
    "emailConfigurationTitle": "تكوين البريد الإلكتروني",
    "alertsTitle": "التنبيهات",
    "calendarTitle": "التقويم",
    "highlightsTitle": "Highlights",
    "serviceManagementTitle": "Service Management",
    "knowledgeBaseTitle": "Knowledge Base",
    "customerCenterTitle": "مركز العملاء"
};
var oneClickChineseSimplified = {
    "salesTitle": "销售",
    "serviceTitle": "服务",
    "marketingTitle": "市场营销",
    "settingsTitle": "设置",
    "helpTitle": "帮助",
    "advancedFindTitle": "高级查找​​",
    "dashboardTitle": "仪表板",
    "whatsNewTitle": "新鲜事",
    "activitiesTitle": "活动",
    "queuesTitle": "队列",
    "serviceCalendarTitle": "服务日历",
    "businessManagementTitle": "业务管理",
    "templatesTitle": "模板",
    "productCatalogTitle": "产品目录",
    "administrationTitle": "管理",
    "dataManagementTitle": "数据管理",
    "systemJobsTitle": "系统作业",
    "documentManagementTitle": "文档管理",
    "auditingTitle": "审核",
    "customizationsTitle": "自定义项",
    "marketplaceTitle": "Marketplace",//sitemap item appears in english
    "emailConfigurationTitle": "电子邮件配置",
    "alertsTitle": "警报",
    "calendarTitle": "日历",
    "highlightsTitle": "Highlights",
    "serviceManagementTitle": "Service Management",
    "knowledgeBaseTitle": "Knowledge Base",
    "customerCenterTitle": "客户中心"
};
var oneClickChineseTraditional = {
    "salesTitle": "銷售",
    "serviceTitle": "服務",
    "marketingTitle": "行銷",
    "settingsTitle": "設定",
    "helpTitle": "說明",
    "advancedFindTitle": "進階​​尋找",
    "dashboardTitle": "儀表板",
    "whatsNewTitle": "最新動態",
    "activitiesTitle": "活動",
    "queuesTitle": "待辦事項",
    "serviceCalendarTitle": "服務行事曆",
    "businessManagementTitle": "商業管理",
    "templatesTitle": "範本",
    "productCatalogTitle": "產品類別目錄",
    "administrationTitle": "管理",
    "dataManagementTitle": "資料管理",
    "systemJobsTitle": "系統作業",
    "documentManagementTitle": "文件管理",
    "auditingTitle": "稽核",
    "customizationsTitle": "自訂",
    "marketplaceTitle": "Marketplace",//sitemap item appears in english
    "emailConfigurationTitle": "電子郵件組態",
    "alertsTitle": "警示",
    "calendarTitle": "行事曆",
    "highlightsTitle": "Highlights",
    "serviceManagementTitle": "Service Management",
    "knowledgeBaseTitle": "Knowledge Base",
    "customerCenterTitle": "客戶中心"
};
var oneClickJapenese = {
    "salesTitle": "営業",
    "serviceTitle": "サービス",
    "marketingTitle": "マーケティング",
    "settingsTitle": "設定",
    "helpTitle": "ヘルプ",
    "advancedFindTitle": "高度な検索​​",
    "dashboardTitle": "ダッシュボード",
    "whatsNewTitle": "新着情報",
    "activitiesTitle": "活動",
    "queuesTitle": "キュー",
    "serviceCalendarTitle": "サービス カレンダー",
    "businessManagementTitle": "事業部管理",
    "templatesTitle": "テンプレート",
    "productCatalogTitle": "製品カタログ",
    "administrationTitle": "管理",
    "dataManagementTitle": "データ管理",
    "systemJobsTitle": "システム ジョブ ",
    "documentManagementTitle": "ドキュメント管理",
    "auditingTitle": "監査",
    "customizationsTitle": "カスタマイズ",
    "marketplaceTitle": "Marketplace",//sitemap item appears in english
    "emailConfigurationTitle": "電子メール アクセス構成",
    "alertsTitle": "通知",
    "calendarTitle": "カレンダー",
    "highlightsTitle": "Highlights",
    "serviceManagementTitle": "Service Management",
    "knowledgeBaseTitle": "Knowledge Base",
    "customerCenterTitle": "カスタマー センター"
};
var oneClickHindi = {
    "salesTitle": "विक्रय",
    "serviceTitle": "सेवा",
    "marketingTitle": "मार्केटिंग",
    "settingsTitle": "सेटिंग्स",
    "helpTitle": "सहायता",
    "advancedFindTitle": "उन्नत खोज",
    "dashboardTitle": "डैशबोर्ड",
    "whatsNewTitle": "डैशबोर्ड",
    "activitiesTitle": "गतिविधियाँ",
    "queuesTitle": "क्यूज़",
    "serviceCalendarTitle": "सेवा कैलेंडर",
    "businessManagementTitle": "व्यवसाय प्रबंधन",
    "templatesTitle": "टेम्पलेट्स",
    "productCatalogTitle": "उत्पाद कैटलॉग",
    "administrationTitle": "व्यवस्थापन",
    "dataManagementTitle": "डेटा प्रबंधन",
    "systemJobsTitle": "सिस्टम कार्य्स",
    "documentManagementTitle": "दस्तावेज़ प्रबंधन",
    "auditingTitle": "ऑडिटिंग",
    "customizationsTitle": "अनुकूलन",
    "marketplaceTitle": "Marketplace",//sitemap item appears in english
    "emailConfigurationTitle": "ईमेल कॉन्फ़िगरेशन",
    "alertsTitle": "चेतावनियाँ",
    "calendarTitle": "कैलेंडर",
    "highlightsTitle": "Highlights",
    "serviceManagementTitle": "Service Management",
    "knowledgeBaseTitle": "Knowledge Base",
    "customerCenterTitle": "ग्राहक केंद्र"
};
var oneClickHebrew = {
    "salesTitle": "מכירות",
    "serviceTitle": "שירות",
    "marketingTitle": "שיווק",
    "settingsTitle": "הגדרות",
    "helpTitle": "עזרה",
    "advancedFindTitle": "חיפוש מתקדם",
    "dashboardTitle": "לוחות מחוונים",
    "whatsNewTitle": "מה חדש",
    "activitiesTitle": "פעילויות",
    "queuesTitle": "תורים",
    "serviceCalendarTitle": "לוח תאריכי שירות",
    "businessManagementTitle": "ניהול עסקי",
    "templatesTitle": "תבניות",
    "productCatalogTitle": "קטלוג מוצרים",
    "administrationTitle": "ניהול",
    "dataManagementTitle": "ניהול נתונים",
    "systemJobsTitle": "משימות מערכת",
    "documentManagementTitle": "ניהול מסמכים",
    "auditingTitle": "ביקורת",
    "customizationsTitle": "התאמות אישיות",
    "marketplaceTitle": "Marketplace",//sitemap item appears in english
    "emailConfigurationTitle": "תצורת דואר אלקטרוני",
    "alertsTitle": "התראות",
    "calendarTitle": "לוח שנה",
    "highlightsTitle": "Highlights",
    "serviceManagementTitle": "Service Management",
    "knowledgeBaseTitle": "Knowledge Base",
    "customerCenterTitle": "מרכז הלקוחות"
};
var oneClickKorean = {
    "salesTitle": "영업",
    "serviceTitle": "서비스",
    "marketingTitle": "마케팅",
    "settingsTitle": "설정",
    "helpTitle": "도움말",
    "advancedFindTitle": "상세하게 찾기",
    "dashboardTitle": "대시보드",
    "whatsNewTitle": "내 담벼락",
    "activitiesTitle": "활동",
    "queuesTitle": "큐",
    "serviceCalendarTitle": "서비스 일정",
    "businessManagementTitle": "비즈니스 관리",
    "templatesTitle": "템플릿",
    "productCatalogTitle": "제품 카탈로그",
    "administrationTitle": "관리",
    "dataManagementTitle": "데이터 관리",
    "systemJobsTitle": "시스템 작업 ",
    "documentManagementTitle": "문서 관리",
    "auditingTitle": "감사",
    "customizationsTitle": "커스터마이제이션",
    "marketplaceTitle": "Marketplace",//sitemap item appears in english
    "emailConfigurationTitle": "전자 메일 구성",
    "alertsTitle": "알림",
    "calendarTitle": "일정",
    "highlightsTitle": "Highlights",
    "serviceManagementTitle": "Service Management",
    "knowledgeBaseTitle": "Knowledge Base",
    "customerCenterTitle": "고객 센터"
};
var oneClickPolish = {
    "salesTitle": "Sprzedaż",
    "serviceTitle": "Usługi",
    "marketingTitle": "Marketing",//sitemap item appears in english
    "settingsTitle": "Ustawienia",
    "helpTitle": "Pomoc",
    "advancedFindTitle": "Szukanie zaawansowane",
    "dashboardTitle": "Pulpity nawigacyjne",
    "whatsNewTitle": "Co nowego",
    "activitiesTitle": "Działania",
    "queuesTitle": "Kolejki",
    "serviceCalendarTitle": "Kalendarz usług",
    "businessManagementTitle": "Zarządzanie podmiotem gospodarczym",
    "templatesTitle": "Szablony",
    "productCatalogTitle": "Katalog produktów",
    "administrationTitle": "Administracja",
    "dataManagementTitle": "Zarządzanie danymi",
    "systemJobsTitle": "Zadania systemowe",
    "documentManagementTitle": "Zarządzanie dokumentami",
    "auditingTitle": "Inspekcja",
    "customizationsTitle": "Dostosowania",
    "marketplaceTitle": "Marketplace",//sitemap item appears in english
    "emailConfigurationTitle": "Konfiguracja poczty e-mail",
    "alertsTitle": "Alerty",
    "calendarTitle": "Kalendarz",
    "highlightsTitle": "Highlights",
    "serviceManagementTitle": "Service Management",
    "knowledgeBaseTitle": "Knowledge Base",
    "customerCenterTitle": "Centrum obsługi klienta"
};
var oneClickThai = {
    "salesTitle": "การขาย",
    "serviceTitle": "การบริการ",
    "marketingTitle": "การตลาด",
    "settingsTitle": "การตั้งค่า",
    "helpTitle": "วิธีใช้",
    "advancedFindTitle": "การค้นหาขั้นสูง",
    "dashboardTitle": "แดชบอร์ด",
    "whatsNewTitle": "มีอะไรใหม่",
    "activitiesTitle": "กิจกรรม",
    "queuesTitle": "คิว",
    "serviceCalendarTitle": "ปฏิทินการบริการ",
    "businessManagementTitle": "การจัดการธุรกิจ",
    "templatesTitle": "แม่แบบ",
    "productCatalogTitle": "แค็ตตาล็อกผลิตภัณฑ์",
    "administrationTitle": "การจัดการ",
    "dataManagementTitle": "การจัดการข้อมูล",
    "systemJobsTitle": "System Jobs", //sitemap item appears in english
    "documentManagementTitle": "การจัดการเอกสาร",
    "auditingTitle": "การตรวจสอบ",
    "customizationsTitle": "การกำหนดเอง",
    "marketplaceTitle": "Marketplace", //sitemap item appears in english
    "emailConfigurationTitle": "การกำหนดค่าอีเมล",
    "alertsTitle": "การแจ้งเตือน",
    "calendarTitle": "ปฏิทิน",
    "highlightsTitle": "Highlights",
    "serviceManagementTitle": "Service Management",
    "knowledgeBaseTitle": "Knowledge Base",
    "customerCenterTitle": "ศูนย์บริการลูกค้า"
};


function GetUserLanguage() {
    // Get User language
    var userLanguage = _Context().getUserLcid();

    // Default is ENGLISH
    var language = oneClickEnglish;

    if (userLanguage == "1031" || userLanguage == "3079" || userLanguage == "5127" || userLanguage == "4103" || userLanguage == "2055") {

        language = oneClickGerman;

    } else if (userLanguage == "3082" || userLanguage == "1034" || userLanguage == "11274" || userLanguage == "16394" || userLanguage == "13322" ||
                userLanguage == "9226" || userLanguage == "5130" || userLanguage == "7178" || userLanguage == "12298" || userLanguage == "17418" ||
                userLanguage == "4106" || userLanguage == "18442" || userLanguage == "22538" || userLanguage == "2058" || userLanguage == "19466" ||
                userLanguage == "6154" || userLanguage == "15370" || userLanguage == "10250" || userLanguage == "20490" || userLanguage == "21514" ||
                userLanguage == "14346" || userLanguage == "8202") {

        language = oneClickSpanish

    } else if (userLanguage == "5121" || userLanguage == "15361" || userLanguage == "3073" || userLanguage == "2049" || userLanguage == "11265" ||
                userLanguage == "13313" || userLanguage == "12289" || userLanguage == "4097" || userLanguage == "6145" || userLanguage == "8193" ||
                userLanguage == "16385" || userLanguage == "1025" || userLanguage == "10241" || userLanguage == "7169" || userLanguage == "14337" ||
                userLanguage == "9217") {

        language = oneClickArabic;

    } else if (userLanguage == "1036" || userLanguage == "2060" || userLanguage == "3084" || userLanguage == "5132" || userLanguage == "6156" ||
                userLanguage == "4108") {

        language = oneClickFrench;

    } else if (userLanguage == "1040" || userLanguage == "2064") {

        language = oneClickItalian;

    } else if (userLanguage == "2070") {

        language = oneClickPortuguesePortugal;

    } else if (userLanguage == "1046") {

        language = oneClickPortugueseBrazil;

    } else if (userLanguage == "1049" || userLanguage == "2073") {

        language = oneClickRussian;

    } else if (userLanguage == "2052" || userLanguage == "4100") {

        language = oneClickChineseSimplified;

    } else if (userLanguage == "1028" || userLanguage == "3076" || userLanguage == "5124") {

        language = oneClickChineseTraditional;

    } else if (userLanguage == "1041") {

        language = oneClickJapenese;

    } else if (userLanguage == "1081") {

        language = oneClickHindi;

    } else if (userLanguage == "1037") {

        language = oneClickHebrew;

    } else if (userLanguage == "1042") {

        language = oneClickKorean;

    } else if (userLanguage == "1045") {

        language = oneClickPolish;

    } else if (userLanguage == "1054") {

        language = oneClickThai;
    }

    return language;
}

function BuildNav(siteMapDoc) {
    var newAdvFindButton = MenuStart();
    var areas = siteMapDoc.selectNodes("/SiteMap/Area");
    var areasCount = areas.length;

    // For internationalization
    var language = GetUserLanguage();

    for (var a = 0; a < areasCount; a++) {
        var area = areas[a].getAttribute("Id");
        var areaTitle = "";
        if (area == "SFA") {
            areaTitle = language["salesTitle"];
        }
        else if (area == "CS") {
            areaTitle = language["serviceTitle"];
        }
        else if (area == "MA") {
            areaTitle = language["marketingTitle"];
        }
        else if (area == "Settings") {
            areaTitle = language["settingsTitle"];
        }
        else if (area == "HLP") {
            areaTitle = language["helpTitle"];
        }
        // If title wasn't found in resource xml get it from sitemap
        if (areaTitle == "") {
            var areaTitleTmp = siteMapDoc.selectSingleNode("//SiteMap/Area[@Id='" + area + "']/Titles/Title[@LCID='" + context.getOrgLcid() + "']/@Title");
            if (areaTitleTmp != null)
                areaTitle = areaTitleTmp.nodeValue;
            else {
                // In some cases Area Tag does not contain subtags that lead to main menu title. In that case, look for "title" attribute
                areaTitleTmp = siteMapDoc.selectSingleNode("//SiteMap/Area[@Id='" + area + "']/@Titldsfsdfe");
                if (areaTitleTmp != null)
                    areaTitle = areaTitleTmp.nodeValue;
                else
                    areaTitle = area;
            }
        }
        //Build submenues for this main menu option
        newAdvFindButton += Buildmenu(areaTitle, area, siteMapDoc);
    }

    newAdvFindButton += MenuEnd(language);
    newAdvFindButton += BuildSyles();
    newAdvFindButton += BuildMenuScript();
    parent.$("#crmLookupMru").prepend(newAdvFindButton);
}

function BuildSyles() {
    newAdvFindButton = "  <style>";
    newAdvFindButton += "  .navActionGroupContainer { top: 55px !Important}";
    newAdvFindButton += "  div.newNavBarMode.ms-crm-TopBarContainer { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"sitemappath=Settings%7cProcessCenter%7cnav_workflow\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmLookupMru { background-color: rgb( 0, 32, 80) !Important}";

    newAdvFindButton += "  #crmContentPanel[src*=\"sitemappath=Settings%7cBusiness_Setting%7cnav_businessmanagement\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"sitemappath=Settings%7cBusiness_Setting%7cnav_template\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"sitemappath=Settings%7cBusiness_Setting%7cnav_productcatalog\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"sitemappath=Settings%7cCustomizations%7cnav_syscust\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"sitemappath=Settings%7cCustomizations%7cnav_solution\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"sitemappath=Settings%7cCustomizations%7cnav_marketplace\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"sitemappath=Settings%7cSystem_Setting%7cnav_datamanagement\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"sitemappath=Settings%7cSystem_Setting%7cnav_systemjobs\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"sitemappath=Settings%7cSystem_Setting%7cnav_documentmanagement\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"sitemappath=Settings%7cSystem_Setting%7cnav_audit\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"sitemappath=Settings%7cSystem_Setting%7cnav_social\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"systemCustomization.aspx\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"sitemappath=Settings%7cSystem_Setting%7cnav_administration\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"sitemappath=Settings%7cBusiness_Setting%7cnav_servicemanagement\"] { top: 55px !Important}";

    newAdvFindButton += "  #crmContentPanel[src*=\"business.aspx?pid=02\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"business.aspx?pid=03\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"business.aspx?pid=02\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"business.aspx?pid=05\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"business.aspx?pid=06\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"business.aspx?pid=08\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"business.aspx?pid=09\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"business.aspx?pid=10\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"business.aspx?pid=11\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"business.aspx?pid=12\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"business.aspx?pid=13\"] { top: 55px !Important}";

    newAdvFindButton += "  #crmContentPanel[src*=\"templates.aspx?pid=01\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"templates.aspx?pid=03\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"templates.aspx?pid=04\"] { top: 55px !Important}";

    newAdvFindButton += "  #crmContentPanel[src*=\"datamanagement.aspx?pid=03\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"datamanagement.aspx?pid=04\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"datamanagement.aspx?pid=05\"] { top: 55px !Important}";

    newAdvFindButton += "  #crmContentPanel[src*=\"audit_area.aspx?pid=03\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"audit_area.aspx?pid=04\"] { top: 55px !Important}";

    newAdvFindButton += "  #crmContentPanel[src*=\"admin.aspx?pid=04\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"admin.aspx?pid=92\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"admin.aspx?pid=14\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"admin.aspx?pid=15\"] { top: 55px !Important}";

    newAdvFindButton += "  #crmContentPanel[src*=\"servicemanagement.aspx?pid=08\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"servicemanagement.aspx?pid=09\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"servicemanagement.aspx?pid=11\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"servicemanagement.aspx?pid=12\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"servicemanagement.aspx?pid=14\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"servicemanagement.aspx?pid=15\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"servicemanagement.aspx?pid=16\"] { top: 55px !Important}";
    newAdvFindButton += "  #crmContentPanel[src*=\"servicemanagement.aspx?pid=17\"] { top: 55px !Important}";

    // For positioning entity title in Quick Create Option
    newAdvFindButton += "  #globalquickcreate_entityinfo_NavBarGloablQuickCreate { top: 60px !Important}";

    // Dimmed headers should include OneClickNav Menu when clicking Quick Create Option
    newAdvFindButton += "  #navbar_overlay_NavBarGloablQuickCreate { height: 59px !Important}";

    // for positioning Quick Create Form
    newAdvFindButton += "  #globalquickcreate_container_NavBarGloablQuickCreate{ top: 90px !Important}";


    newAdvFindButton += "   .level1";
    newAdvFindButton += "   {";
    newAdvFindButton += "       color: White !important;";
    newAdvFindButton += "       margin-right:5px;";
    newAdvFindButton += '       font-family: "Segoe UI" , "Segoe" , Tahoma, Helvetica, Arial, sans-serif !important;';
    newAdvFindButton += "       background-color: rgb( 0, 32, 80);";
    newAdvFindButton += "       font-variant: small-caps;";
    newAdvFindButton += "   }";
    newAdvFindButton += "   .level2";
    newAdvFindButton += "   {";
    newAdvFindButton += "       color: rgb( 0, 32, 80);";
    newAdvFindButton += '       font-family: "Segoe UI" , "Segoe" , Tahoma, Helvetica, Arial, sans-serif !important;';
    newAdvFindButton += "       font-size: small;";
    newAdvFindButton += "       background-color: rgb( 223, 226, 232);";
    newAdvFindButton += "       margin: 5px;";
    newAdvFindButton += "       z-index: 10000 !important;";
    newAdvFindButton += "   }";
    newAdvFindButton += "   .level2 li:hover";
    newAdvFindButton += "   {";
    newAdvFindButton += "       color: White !important;   ";
    newAdvFindButton += "       background-color: rgb( 0, 32, 80) !important;    ";
    newAdvFindButton += "   }";

    var context = _Context();

    newAdvFindButton += "   .navseparator";
    newAdvFindButton += "   {";
    newAdvFindButton += "       background-image: url( '" + context.getClientUrl() + "/WebResources/remcod_sep.png' );    ";
    newAdvFindButton += "       background-repeat: repeat-x;    ";
    newAdvFindButton += "   }";

    newAdvFindButton += "   .level2 a:hover";
    newAdvFindButton += "   {";
    newAdvFindButton += "       color: White !important;    ";
    newAdvFindButton += "       background-color: rgb( 0, 32, 80) !important;    ";
    newAdvFindButton += "   }";

    newAdvFindButton += "	#Menu1 img.icon { border-style:none;vertical-align:middle; }";
    newAdvFindButton += "	#Menu1 { width: 100% }";

    newAdvFindButton += "   #Menu1 img.separator";
    newAdvFindButton += "   {";
    newAdvFindButton += "       border-style:none;display:block;    ";
    newAdvFindButton += "       width:100%; ";
    newAdvFindButton += "       height:1px;    ";
    newAdvFindButton += "       cursor: default;    ";
    newAdvFindButton += "   }";

    newAdvFindButton += "#Menu1 img.horizontal-separator { border-style:none;vertical-align:middle; }";
    newAdvFindButton += "#Menu1 ul { list-style:none;margin:0;padding:0;width:auto; }";
    newAdvFindButton += "#Menu1 ul.dynamic { z-index:1; overflow-y: auto; max-height: 600px; }";
    newAdvFindButton += "#Menu1 a { font-family:Arial,Gill Sans;text-decoration:none;white-space:nowrap;display:block; }";
    newAdvFindButton += "#Menu1 a.static { padding-left:0.15em;padding-right:0.15em; }";
    newAdvFindButton += "#Menu1 a.popout { background-image:url('/_imgs/NavBar/ArrowDown.png');background-repeat:no-repeat;background-position:right center;padding-right:14px; }";
    newAdvFindButton += "#Menu1 a.level1 { text-decoration:none;border-style:none; }";
    newAdvFindButton += "#Menu1 a.level2 { text-decoration:none;border-style:none; }";

    newAdvFindButton += "  </style>";
    return newAdvFindButton;
}

function BuildMenuScript() {
    var menuscript = "<script>window.Sys || (window.Sys = {}); Sys.WebForms || (Sys.WebForms = {}); Sys.WebForms.Menu = function (n) { var u, f, s, t, e, o, i, r; for (this.items = [], this.depth = n.depth || 1, this.parentMenuItem = n.parentMenuItem, this.element = Sys.WebForms.Menu._domHelper.getElement(n.element), this.element.tagName === \"DIV\" ? (u = this.element, this.element = Sys.WebForms.Menu._domHelper.firstChild(u), this.element.tabIndex = n.tabIndex || 0, n.element = u, n.menu = this, this.container = new Sys.WebForms._MenuContainer(n), Sys.WebForms.Menu._domHelper.setFloat(this.element, this.container.rightToLeft ? \"right\" : \"left\")) : (this.container = n.container, this.keyMap = n.keyMap), Sys.WebForms.Menu._elementObjectMapper.map(this.element, this), this.parentMenuItem && this.parentMenuItem.parentMenu && (this.parentMenu = this.parentMenuItem.parentMenu, this.rootMenu = this.parentMenu.rootMenu, this.element.id || (this.element.id = (this.container.element.id || \"menu\") + \":submenu:\" + Sys.WebForms.Menu._elementObjectMapper._computedId), this.depth > this.container.staticDisplayLevels ? (this.displayMode = \"dynamic\", this.element.style.display = \"none\", this.element.style.position = \"absolute\", this.rootMenu && this.container.orientation === \"horizontal\" && this.parentMenu.isStatic() ? (this.element.style.top = \"100%\", this.container.rightToLeft ? this.element.style.right = \"0px\" : this.element.style.left = \"0px\") : (this.element.style.top = \"0px\", this.container.rightToLeft ? this.element.style.right = \"100%\" : this.element.style.left = \"100%\"), this.keyMap = this.container.rightToLeft ? Sys.WebForms.Menu._keyboardMapping.verticalRtl : Sys.WebForms.Menu._keyboardMapping.vertical) : (this.displayMode = \"static\", this.element.style.display = \"block\", this.container.orientation === \"horizontal\" && Sys.WebForms.Menu._domHelper.setFloat(this.element, this.container.rightToLeft ? \"right\" : \"left\"))), Sys.WebForms.Menu._domHelper.appendCssClass(this.element, this.displayMode), f = this.element.childNodes, s = f.length, t = 0; t < s; t++) (e = f[t], e.nodeType === 1) && (o = null, this.parentMenuItem && (o = this.parentMenuItem.topLevelMenuItem), i = new Sys.WebForms.MenuItem(this, e, o), r = this.items[this.items.length - 1], r && (i.previousSibling = r, r.nextSibling = i), this.items[this.items.length] = i) }; Sys.WebForms.Menu.prototype = { blur: function () { this.container && this.container.blur() }, collapse: function () { this.each(function (n) { n.hover(!1); n.blur(); var t = n.childMenu; t && t.collapse() }); this.hide() }, doDispose: function () { this.each(function (n) { n.doDispose() }) }, each: function (n) { for (var i = this.items.length, t = 0; t < i; t++) n(this.items[t]) }, firstChild: function () { return this.items[0] }, focus: function () { this.container && this.container.focus() }, get_displayed: function () { return this.element.style.display !== \"none\" }, get_focused: function () { return this.container ? this.container.focused : !1 }, handleKeyPress: function (n) { if (this.keyMap.contains(n)) { if (this.container.focusedMenuItem) { this.container.focusedMenuItem.navigate(n); return } var t = this.firstChild(); t && this.container.navigateTo(t) } }, hide: function () { this.get_displayed() && (this.each(function (n) { n.childMenu && n.childMenu.hide() }), this.isRoot() || (this.get_focused() && this.container.navigateTo(this.parentMenuItem), this.element.style.display = \"none\")) }, isRoot: function () { return this.rootMenu === this }, isStatic: function () { return this.displayMode === \"static\" }, lastChild: function () { return this.items[this.items.length - 1] }, show: function () { this.element.style.display = \"block\" } }; Sys.WebForms.Menu.registerClass && Sys.WebForms.Menu.registerClass(\"Sys.WebForms.Menu\"); Sys.WebForms.MenuItem = function (n, t, i) { for (this.keyMap = n.keyMap, this.parentMenu = n, this.container = n.container, this.element = t, this.topLevelMenuItem = i || this, this._anchor = Sys.WebForms.Menu._domHelper.firstChild(t) ; this._anchor && this._anchor.tagName !== \"A\";) this._anchor = Sys.WebForms.Menu._domHelper.nextSibling(this._anchor); if (this._anchor) { this._anchor.tabIndex = -1; for (var r = this._anchor; r && r.tagName !== \"UL\";) r = Sys.WebForms.Menu._domHelper.nextSibling(r); r && (this.childMenu = new Sys.WebForms.Menu({ element: r, parentMenuItem: this, depth: n.depth + 1, container: this.container, keyMap: this.keyMap }), this.childMenu.isStatic() || (Sys.WebForms.Menu._domHelper.appendCssClass(this.element, \"has-popup\"), Sys.WebForms.Menu._domHelper.appendAttributeValue(this.element, \"aria-haspopup\", this.childMenu.element.id))) } Sys.WebForms.Menu._elementObjectMapper.map(t, this); Sys.WebForms.Menu._domHelper.appendAttributeValue(t, \"role\", \"menuitem\"); Sys.WebForms.Menu._domHelper.appendCssClass(t, n.displayMode); this._anchor && Sys.WebForms.Menu._domHelper.appendCssClass(this._anchor, n.displayMode); this.element.style.position = \"relative\"; this.parentMenu.depth == 1 && this.container.orientation == \"horizontal\" && Sys.WebForms.Menu._domHelper.setFloat(this.element, this.container.rightToLeft ? \"right\" : \"left\"); this.container.disabled || (Sys.WebForms.Menu._domHelper.addEvent(this.element, \"mouseover\", Sys.WebForms.MenuItem._onmouseover), Sys.WebForms.Menu._domHelper.addEvent(this.element, \"mouseout\", Sys.WebForms.MenuItem._onmouseout)) }; Sys.WebForms.MenuItem.prototype = { applyUp: function (n, t) { t = t || function (n) { return n }; for (var i = this, r = null; t(i) ;) n(i), r = i, i = i.parentMenu.parentMenuItem; return r }, blur: function () { this.setTabIndex(-1) }, doDispose: function () { Sys.WebForms.Menu._domHelper.removeEvent(this.element, \"mouseover\", Sys.WebForms.MenuItem._onmouseover); Sys.WebForms.Menu._domHelper.removeEvent(this.element, \"mouseout\", Sys.WebForms.MenuItem._onmouseout); this.childMenu && this.childMenu.doDispose() }, focus: function () { this.parentMenu.get_displayed() || this.parentMenu.show(); this.setTabIndex(0); this.container.focused = !0; this._anchor.focus() }, get_highlighted: function () { return /(^|\s)highlighted(\s|$)/.test(this._anchor.className) }, getTabIndex: function () { return this._anchor.tabIndex }, highlight: function (n) { n ? (this.applyUp(function (n) { n.parentMenu.parentMenuItem.highlight(!0) }, function (n) { return !n.parentMenu.isStatic() && n.parentMenu.parentMenuItem }), Sys.WebForms.Menu._domHelper.appendCssClass(this._anchor, \"highlighted\")) : (Sys.WebForms.Menu._domHelper.removeCssClass(this._anchor, \"highlighted\"), this.setTabIndex(-1)) }, hover: function (n) { var r, i, t; if (n) r = this.container.hoveredMenuItem, r && r.hover(!1), i = this.container.focusedMenuItem, i && i !== this && i.hover(!1), this.applyUp(function (n) { n.childMenu && !n.childMenu.get_displayed() && n.childMenu.show() }), this.container.hoveredMenuItem = this, this.highlight(!0); else for (t = this; t;) t.highlight(!1), t.childMenu && (t.childMenu.isStatic() || t.childMenu.hide()), t = t.parentMenu.parentMenuItem }, isSiblingOf: function (n) { return n.parentMenu === this.parentMenu }, mouseout: function () { var i = this, n = this.container.pendingMouseoutId, t = this.container.disappearAfter; n && window.clearTimeout(n); t > -1 && (this.container.pendingMouseoutId = window.setTimeout(function () { i.hover(!1) }, t)) }, mouseover: function () { var n = this.container.pendingMouseoutId; n && (window.clearTimeout(n), this.container.pendingMouseoutId = null); this.hover(!0); this.container.menu.get_focused() && this.container.navigateTo(this) }, navigate: function (n) { switch (this.keyMap[n]) { case this.keyMap.next: this.navigateNext(); break; case this.keyMap.previous: this.navigatePrevious(); break; case this.keyMap.child: this.navigateChild(); break; case this.keyMap.parent: this.navigateParent(); break; case this.keyMap.tab: this.navigateOut() } }, navigateChild: function () { var i = this.childMenu, t, n; if (i) t = i.firstChild(), t && this.container.navigateTo(t); else if (this.container.orientation === \"horizontal\") { if (n = this.topLevelMenuItem.nextSibling || this.topLevelMenuItem.parentMenu.firstChild(), n == this.topLevelMenuItem) return; this.topLevelMenuItem.childMenu.hide(); this.container.navigateTo(n); n.childMenu && this.container.navigateTo(n.childMenu.firstChild()) } }, navigateNext: function () { this.childMenu && this.childMenu.hide(); var n = this.nextSibling; !n && this.parentMenu.isRoot() && (n = this.parentMenu.parentMenuItem, n && (n = n.nextSibling)); n || (n = this.parentMenu.firstChild()); n && this.container.navigateTo(n) }, navigateOut: function () { this.parentMenu.blur() }, navigateParent: function () { var t = this.parentMenu, i = this.container.orientation === \"horizontal\", n; if (t) { if (i && this.childMenu && t.isRoot()) { this.navigateChild(); return } t.parentMenuItem && !t.isRoot() && (i && this.parentMenu.depth === 2 ? (n = this.parentMenu.parentMenuItem.previousSibling, n || (n = this.parentMenu.rootMenu.lastChild()), this.topLevelMenuItem.childMenu.hide(), this.container.navigateTo(n), n.childMenu && this.container.navigateTo(n.childMenu.firstChild())) : this.parentMenu.hide()) } }, navigatePrevious: function () { var n, t; this.childMenu && this.childMenu.hide(); n = this.previousSibling; n && (t = n.childMenu, t && t.isRoot() && (n = t.lastChild())); !n && this.parentMenu.isRoot() && (n = this.parentMenu.parentMenuItem); n || (n = this.parentMenu.lastChild()); n && this.container.navigateTo(n) }, setTabIndex: function (n) { this._anchor && (this._anchor.tabIndex = n) } }; Sys.WebForms.MenuItem._onmouseout = function (n) { var t = Sys.WebForms.Menu._elementObjectMapper.getMappedObject(this); t && (t.mouseout(), Sys.WebForms.Menu._domHelper.cancelEvent(n)) }; Sys.WebForms.MenuItem._onmouseover = function (n) { var t = Sys.WebForms.Menu._elementObjectMapper.getMappedObject(this); t && (t.mouseover(), Sys.WebForms.Menu._domHelper.cancelEvent(n)) }; Sys.WebForms.Menu._domHelper = { addEvent: function (n, t, i, r) { n.addEventListener ? n.addEventListener(t, i, !!r) : n[\"on\" + t] = i }, appendAttributeValue: function (n, t, i) { this.updateAttributeValue(\"append\", n, t, i) }, appendCssClass: function (n, t) { this.updateClassName(\"append\", n, name, t) }, appendString: function (n, t, i) { var r = n(), u; if (!r) { t(i); return } (u = this._regexes.getRegex(\"(^| )\" + i + \"($| )\"), u.test(r)) || t(r + \" \" + i) }, cancelEvent: function (n) { var t = n || window.event; t && (t.cancelBubble = !0, t.stopPropagation && t.stopPropagation()) }, contains: function (n, t) { for (; t && t !== n; t = t.parentNode); return !!t }, firstChild: function (n) { var t = n.firstChild; return t && t.nodeType !== 1 && (t = this.nextSibling(t)), t }, getElement: function (n) { return typeof n == \"string\" ? document.getElementById(n) : n }, getElementDirection: function (n) { return n ? n.dir ? n.dir : this.getElementDirection(n.parentNode) : \"ltr\" }, getKeyCode: function (n) { return n.keyCode || n.charCode || 0 }, insertAfter: function (n, t) { var i = n.nextSibling; i ? n.parentNode.insertBefore(t, i) : n.parentNode && n.parentNode.appendChild(t) }, nextSibling: function (n) { for (var t = n.nextSibling; t;) { if (t.nodeType === 1) return t; t = t.nextSibling } }, removeAttributeValue: function (n, t, i) { this.updateAttributeValue(\"remove\", n, t, i) }, removeCssClass: function (n, t) { this.updateClassName(\"remove\", n, name, t) }, removeEvent: function (n, t, i, r) { n.removeEventListener ? n.removeEventListener(t, i, !!r) : n.detachEvent && n.detachEvent(\"on\" + t, i); n[\"on\" + t] = null }, removeString: function (n, t, i) { var r = n(), u; r && (u = this._regexes.getRegex(\"(\\s|\\b)\" + i + \"$|\\b\" + i + \"\\s+\"), t(r.replace(u, \"\"))) }, setFloat: function (n, t) { n.style.styleFloat = t; n.style.cssFloat = t }, updateAttributeValue: function (n, t, i, r) { this[n + \"String\"](function () { return t.getAttribute(i) }, function (n) { t.setAttribute(i, n) }, r) }, updateClassName: function (n, t, i, r) { this[n + \"String\"](function () { return t.className }, function (n) { t.className = n }, r) }, _regexes: { getRegex: function (n) { var t = this[n]; return t || (this[n] = t = new RegExp(n)), t } } }; Sys.WebForms.Menu._elementObjectMapper = { _computedId: 0, _mappings: {}, _mappingIdName: \"Sys.WebForms.Menu.Mapping\", getMappedObject: function (n) { var t = n[this._mappingIdName]; if (t) return this._mappings[this._mappingIdName + \":\" + t] }, map: function (n, t) { var r = n[this._mappingIdName], i; r !== t && (i = n[this._mappingIdName] || n.id || \"%\" + ++this._computedId, n[this._mappingIdName] = i, this._mappings[this._mappingIdName + \":\" + i] = t, t.mappingId = i) } }; Sys.WebForms.Menu._keyboardMapping = new function () { var n = 37, t = 38, i = 39, r = 40, u = 9, f = 27; this.vertical = { next: 0, previous: 1, child: 2, parent: 3, tab: 4 }; this.vertical[r] = this.vertical.next; this.vertical[t] = this.vertical.previous; this.vertical[i] = this.vertical.child; this.vertical[n] = this.vertical.parent; this.vertical[u] = this.vertical[f] = this.vertical.tab; this.verticalRtl = { next: 0, previous: 1, child: 2, parent: 3, tab: 4 }; this.verticalRtl[r] = this.verticalRtl.next; this.verticalRtl[t] = this.verticalRtl.previous; this.verticalRtl[n] = this.verticalRtl.child; this.verticalRtl[i] = this.verticalRtl.parent; this.verticalRtl[u] = this.verticalRtl[f] = this.verticalRtl.tab; this.horizontal = { next: 0, previous: 1, child: 2, parent: 3, tab: 4 }; this.horizontal[i] = this.horizontal.next; this.horizontal[n] = this.horizontal.previous; this.horizontal[r] = this.horizontal.child; this.horizontal[t] = this.horizontal.parent; this.horizontal[u] = this.horizontal[f] = this.horizontal.tab; this.horizontalRtl = { next: 0, previous: 1, child: 2, parent: 3, tab: 4 }; this.horizontalRtl[i] = this.horizontalRtl.previous; this.horizontalRtl[n] = this.horizontalRtl.next; this.horizontalRtl[r] = this.horizontalRtl.child; this.horizontalRtl[t] = this.horizontalRtl.parent; this.horizontalRtl[u] = this.horizontalRtl[f] = this.horizontalRtl.tab; this.horizontal.contains = this.horizontalRtl.contains = this.vertical.contains = this.verticalRtl.contains = function (n) { return this[n] != null } }; Sys.WebForms._MenuContainer = function (n) { var i, t; this.focused = !1; this.disabled = n.disabled; this.staticDisplayLevels = n.staticDisplayLevels || 1; this.element = n.element; this.orientation = n.orientation || \"vertical\"; this.disappearAfter = n.disappearAfter; this.rightToLeft = Sys.WebForms.Menu._domHelper.getElementDirection(this.element) === \"rtl\"; Sys.WebForms.Menu._elementObjectMapper.map(this.element, this); this.menu = n.menu; this.menu.rootMenu = this.menu; this.menu.displayMode = \"static\"; this.menu.element.style.position = \"relative\"; this.menu.element.style.width = \"auto\"; this.orientation === \"vertical\" ? (Sys.WebForms.Menu._domHelper.appendAttributeValue(this.menu.element, \"role\", \"menu\"), this.menu.keyMap = this.rightToLeft ? Sys.WebForms.Menu._keyboardMapping.verticalRtl : Sys.WebForms.Menu._keyboardMapping.vertical) : (Sys.WebForms.Menu._domHelper.appendAttributeValue(this.menu.element, \"role\", \"menubar\"), this.menu.keyMap = this.rightToLeft ? Sys.WebForms.Menu._keyboardMapping.horizontalRtl : Sys.WebForms.Menu._keyboardMapping.horizontal); i = document.createElement(\"div\"); i.style.clear = this.rightToLeft ? \"right\" : \"left\"; this.element.appendChild(i); Sys.WebForms.Menu._domHelper.setFloat(this.element, this.rightToLeft ? \"right\" : \"left\"); Sys.WebForms.Menu._domHelper.insertAfter(this.element, i); this.disabled || (Sys.WebForms.Menu._domHelper.addEvent(this.menu.element, \"focus\", this._onfocus, !0), Sys.WebForms.Menu._domHelper.addEvent(this.menu.element, \"keydown\", this._onkeydown), t = this, this.element.dispose = function () { t.element.dispose && (t.element.dispose = null, Sys.WebForms.Menu._domHelper.removeEvent(t.menu.element, \"focus\", t._onfocus, !0), Sys.WebForms.Menu._domHelper.removeEvent(t.menu.element, \"keydown\", t._onkeydown), t.menu.doDispose()) }, Sys.WebForms.Menu._domHelper.addEvent(window, \"unload\", function () { t.element.dispose && t.element.dispose() })) }; Sys.WebForms._MenuContainer.prototype = { blur: function () { this.focused = !1; this.isBlurring = !1; this.menu.collapse(); this.focusedMenuItem = null }, focus: function () { this.focused = !0 }, navigateTo: function (n) { this.focusedMenuItem && this.focusedMenuItem !== this && this.focusedMenuItem.highlight(!1); n.highlight(!0); n.focus(); this.focusedMenuItem = n }, _onfocus: function (n) { var t = n || window.event; t.srcElement && this && Sys.WebForms.Menu._domHelper.contains(this.element, t.srcElement) && (this.focused || this.focus()) }, _onkeydown: function (n) { var t = Sys.WebForms.Menu._elementObjectMapper.getMappedObject(this), i = Sys.WebForms.Menu._domHelper.getKeyCode(n || window.event); t && t.handleKeyPress(i) } };";
    menuscript += "var oneclickmenu = new Sys.WebForms.Menu({ element: 'Menu1', disappearAfter: 500, orientation: 'horizontal', tabIndex: 0, disabled: false }); ";
    menuscript += "$(window).resize(function () { $('#Menu1 ul.dynamic').css('max-height', $(window).height() - 20);  }); $('#Menu1 ul.dynamic').css('max-height', $(window).height() - 20);";

    menuscript += 'function loadIframe(url) { var o = new Object(); o.uri = url;  if (window.top && window.top.document.getElementById("navBar") && window.top.document.getElementById("navBar").control.raiseNavigateRequest) window.top.document.getElementById("navBar").control.raiseNavigateRequest(o);  oneclickmenu.collapse()}';
    menuscript += "</script>";
    return menuscript;
}
typeof SDK == "undefined" && (SDK = { __namespace: !0 }); SDK.REST = { _context: function () { if (typeof GetGlobalContext != "undefined") return GetGlobalContext(); if (typeof Xrm != "undefined") return Xrm.Page.context; throw new Error("Context is not available."); }, _getServerUrl: function () { if (this._context().getClientUrl) return this._context().getClientUrl(); var n = this._context().getServerUrl(); return n.match(/\/$/) && (n = n.substring(0, n.length - 1)), n }, _ODataPath: function () { return this._getServerUrl() + "/XRMServices/2011/OrganizationData.svc/" }, _errorHandler: function (n) { if (n.status == 12029) return new Error("The attempt to connect to the server failed."); if (n.status == 12007) return new Error("The server name could not be resolved."); var t; try { t = JSON.parse(n.responseText).error.message.value } catch (i) { t = n.responseText } return new Error("Error : " + n.status + ": " + n.statusText + ": " + t) }, _dateReviver: function (n, t) { var i; return typeof t == "string" && (i = /Date\(([-+]?\d+)\)/.exec(t), i) ? new Date(parseInt(t.replace("/Date(", "").replace(")/", ""), 10)) : t }, _parameterCheck: function (n, t) { if (typeof n == "undefined" || n === null) throw new Error(t); }, _stringParameterCheck: function (n, t) { if (typeof n != "string") throw new Error(t); }, _callbackParameterCheck: function (n, t) { if (typeof n != "function") throw new Error(t); }, createRecord: function (n, t, i, r) { this._parameterCheck(n, "SDK.REST.createRecord requires the object parameter."); this._stringParameterCheck(t, "SDK.REST.createRecord requires the type parameter is a string."); this._callbackParameterCheck(i, "SDK.REST.createRecord requires the successCallback is a function."); this._callbackParameterCheck(r, "SDK.REST.createRecord requires the errorCallback is a function."); var u = new XMLHttpRequest; u.open("POST", encodeURI(this._ODataPath() + t + "Set"), !0); u.setRequestHeader("Accept", "application/json"); u.setRequestHeader("Content-Type", "application/json; charset=utf-8"); u.onreadystatechange = function () { this.readyState == 4 && (this.status == 201 ? i(JSON.parse(this.responseText, SDK.REST._dateReviver).d) : r(SDK.REST._errorHandler(this))) }; u.send(JSON.stringify(n)) }, retrieveRecord: function (n, t, i, r, u, f) { var e, s, o; this._stringParameterCheck(n, "SDK.REST.retrieveRecord requires the id parameter is a string."); this._stringParameterCheck(t, "SDK.REST.retrieveRecord requires the type parameter is a string."); i != null && this._stringParameterCheck(i, "SDK.REST.retrieveRecord requires the select parameter is a string."); r != null && this._stringParameterCheck(r, "SDK.REST.retrieveRecord requires the expand parameter is a string."); this._callbackParameterCheck(u, "SDK.REST.retrieveRecord requires the successCallback parameter is a function."); this._callbackParameterCheck(f, "SDK.REST.retrieveRecord requires the errorCallback parameter is a function."); e = ""; (i != null || r != null) && (e = "?", i != null && (s = "$select=" + i, r != null && (s = s + "," + r), e = e + s), r != null && (e = e + "&$expand=" + r)); o = new XMLHttpRequest; o.open("GET", encodeURI(this._ODataPath() + t + "Set(guid'" + n + "')" + e), !0); o.setRequestHeader("Accept", "application/json"); o.setRequestHeader("Content-Type", "application/json; charset=utf-8"); o.onreadystatechange = function () { this.readyState == 4 && (this.status == 200 ? u(JSON.parse(this.responseText, SDK.REST._dateReviver).d) : f(SDK.REST._errorHandler(this))) }; o.send() }, updateRecord: function (n, t, i, r, u) { this._stringParameterCheck(n, "SDK.REST.updateRecord requires the id parameter."); this._parameterCheck(t, "SDK.REST.updateRecord requires the object parameter."); this._stringParameterCheck(i, "SDK.REST.updateRecord requires the type parameter."); this._callbackParameterCheck(r, "SDK.REST.updateRecord requires the successCallback is a function."); this._callbackParameterCheck(u, "SDK.REST.updateRecord requires the errorCallback is a function."); var f = new XMLHttpRequest; f.open("POST", encodeURI(this._ODataPath() + i + "Set(guid'" + n + "')"), !0); f.setRequestHeader("Accept", "application/json"); f.setRequestHeader("Content-Type", "application/json; charset=utf-8"); f.setRequestHeader("X-HTTP-Method", "MERGE"); f.onreadystatechange = function () { this.readyState == 4 && (this.status == 204 || this.status == 1223 ? r() : u(SDK.REST._errorHandler(this))) }; f.send(JSON.stringify(t)) }, updateRecordSync: function (n, t, i, r, u) { this._stringParameterCheck(n, "SDK.REST.updateRecord requires the id parameter."); this._parameterCheck(t, "SDK.REST.updateRecord requires the object parameter."); this._stringParameterCheck(i, "SDK.REST.updateRecord requires the type parameter."); this._callbackParameterCheck(r, "SDK.REST.updateRecord requires the successCallback is a function."); this._callbackParameterCheck(u, "SDK.REST.updateRecord requires the errorCallback is a function."); var f = new XMLHttpRequest; f.open("POST", encodeURI(this._ODataPath() + i + "Set(guid'" + n + "')"), !1); f.setRequestHeader("Accept", "application/json"); f.setRequestHeader("Content-Type", "application/json; charset=utf-8"); f.setRequestHeader("X-HTTP-Method", "MERGE"); f.onreadystatechange = function () { this.readyState == 4 && (this.status == 204 || this.status == 1223 ? r() : u(SDK.REST._errorHandler(this))) }; f.send(JSON.stringify(t)) }, deleteRecord: function (n, t, i, r) { this._stringParameterCheck(n, "SDK.REST.deleteRecord requires the id parameter."); this._stringParameterCheck(t, "SDK.REST.deleteRecord requires the type parameter."); this._callbackParameterCheck(i, "SDK.REST.deleteRecord requires the successCallback is a function."); this._callbackParameterCheck(r, "SDK.REST.deleteRecord requires the errorCallback is a function."); var u = new XMLHttpRequest; u.open("POST", encodeURI(this._ODataPath() + t + "Set(guid'" + n + "')"), !0); u.setRequestHeader("Accept", "application/json"); u.setRequestHeader("Content-Type", "application/json; charset=utf-8"); u.setRequestHeader("X-HTTP-Method", "DELETE"); u.onreadystatechange = function () { this.readyState == 4 && (this.status == 204 || this.status == 1223 ? i() : r(SDK.REST._errorHandler(this))) }; u.send() }, retrieveMultipleRecords: function (n, t, i, r, u) { var e, f; this._stringParameterCheck(n, "SDK.REST.retrieveMultipleRecords requires the type parameter is a string."); t != null && this._stringParameterCheck(t, "SDK.REST.retrieveMultipleRecords requires the options parameter is a string."); this._callbackParameterCheck(i, "SDK.REST.retrieveMultipleRecords requires the successCallback parameter is a function."); this._callbackParameterCheck(r, "SDK.REST.retrieveMultipleRecords requires the errorCallback parameter is a function."); this._callbackParameterCheck(u, "SDK.REST.retrieveMultipleRecords requires the OnComplete parameter is a function."); t != null && (e = t.charAt(0) != "?" ? "?" + t : t); f = new XMLHttpRequest; f.open("GET", this._ODataPath() + n + "Set" + e, !0); f.setRequestHeader("Accept", "application/json"); f.setRequestHeader("Content-Type", "application/json; charset=utf-8"); f.onreadystatechange = function () { var t, f; this.readyState == 4 && (this.status == 200 ? (t = JSON.parse(this.responseText, SDK.REST._dateReviver).d, i(t.results), t.__next != null ? (f = t.__next.substring((SDK.REST._ODataPath() + n + "Set").length), SDK.REST.retrieveMultipleRecords(n, f, i, r, u)) : u()) : r(SDK.REST._errorHandler(this))) }; f.send() }, retrieveRecordsExist: function (n, t) { var u, i, r; if (this._stringParameterCheck(n, "SDK.REST.retrieveMultipleRecords requires the type parameter is a string."), t != null && this._stringParameterCheck(t, "SDK.REST.retrieveMultipleRecords requires the options parameter is a string."), t != null && (u = t.charAt(0) != "?" ? "?" + t : t), i = new XMLHttpRequest, i.open("GET", this._ODataPath() + n + "Set" + u + "&$top=1", !1), i.setRequestHeader("Accept", "application/json"), i.setRequestHeader("Content-Type", "application/json; charset=utf-8"), i.send(), this.readyState == 4) if (this.status == 200) { if (r = JSON.parse(this.responseText, SDK.REST._dateReviver).d, r.results != null && r.results[0] != null) return !0 } else SDK.REST._errorHandler(this) }, associateRecords: function (n, t, i, r, u, f, e) { var o, s; this._stringParameterCheck(n, "SDK.REST.associateRecords requires the parentId parameter is a string."); this._stringParameterCheck(t, "SDK.REST.associateRecords requires the parentType parameter is a string."); this._stringParameterCheck(i, "SDK.REST.associateRecords requires the relationshipName parameter is a string."); this._stringParameterCheck(r, "SDK.REST.associateRecords requires the childId parameter is a string."); this._stringParameterCheck(u, "SDK.REST.associateRecords requires the childType parameter is a string."); this._callbackParameterCheck(f, "SDK.REST.associateRecords requires the successCallback parameter is a function."); this._callbackParameterCheck(e, "SDK.REST.associateRecords requires the errorCallback parameter is a function."); o = new XMLHttpRequest; o.open("POST", encodeURI(this._ODataPath() + t + "Set(guid'" + n + "')/$links/" + i), !0); o.setRequestHeader("Accept", "application/json"); o.setRequestHeader("Content-Type", "application/json; charset=utf-8"); o.onreadystatechange = function () { this.readyState == 4 && (this.status == 204 || this.status == 1223 ? f() : e(SDK.REST._errorHandler(this))) }; s = {}; s.uri = this._ODataPath() + "/" + u + "Set(guid'" + r + "')"; o.send(JSON.stringify(s)) }, disassociateRecords: function (n, t, i, r, u, f) { this._stringParameterCheck(n, "SDK.REST.disassociateRecords requires the parentId parameter is a string."); this._stringParameterCheck(t, "SDK.REST.disassociateRecords requires the parentType parameter is a string."); this._stringParameterCheck(i, "SDK.REST.disassociateRecords requires the relationshipName parameter is a string."); this._stringParameterCheck(r, "SDK.REST.disassociateRecords requires the childId parameter is a string."); this._callbackParameterCheck(u, "SDK.REST.disassociateRecords requires the successCallback parameter is a function."); this._callbackParameterCheck(f, "SDK.REST.disassociateRecords requires the errorCallback parameter is a function."); var e = new XMLHttpRequest; e.open("POST", encodeURI(this._ODataPath() + t + "Set(guid'" + n + "')/$links/" + i + "(guid'" + r + "')"), !0); e.setRequestHeader("Accept", "application/json"); e.setRequestHeader("Content-Type", "application/json; charset=utf-8"); e.setRequestHeader("X-HTTP-Method", "DELETE"); e.onreadystatechange = function () { this.readyState == 4 && (this.status == 204 || this.status == 1223 ? u() : f(SDK.REST._errorHandler(this))) }; e.send() }, __namespace: !0 };
SDK = window.SDK || { __namespace: !0 }, SDK.Metadata = SDK.Metadata || { __namespace: !0 }, SDK.Metadata.Query = SDK.Metadata.Query || { __namespace: !0 }, SDK.Metadata.Query.ValueEnums = SDK.Metadata.Query.ValueEnums || { __namespace: !0 }, function () { function u() { var n = "Context is not available."; return typeof GetGlobalContext != "undefined" ? GetGlobalContext() : typeof Xrm != "undefined" ? Xrm.Page.context : new Error(n) } function h() { if (typeof u().getClientUrl != "undefined") return u().getClientUrl(); var serverUrl = u().getServerUrl(); if (serverUrl.match(/\/$/)) { serverUrl = serverUrl.substring(0, serverUrl.length - 1); } return serverUrl; } function o(n, u, f, e) { var h, w, p, l, o, c, y, k, d; if (n.readyState == 4) if (n.onreadystatechange = null, n.status == 200) { h = n.responseXML; try { s(h) } catch (tt) { } var nt = a(h, "//a:Results/a:KeyValuePairOfstringanyType/b:value[../b:key/text()='ServerVersionStamp']"), b = [], g = i(h, "//a:Results/a:KeyValuePairOfstringanyType/b:value[../b:key/text()='EntityMetadata']"); for (o = 0; o < g.childNodes.length; o++) w = r(g.childNodes[o]), w._type = "EntityMetadata", b.push(w); if (p = {}, l = i(h, "//a:Results/a:KeyValuePairOfstringanyType/b:value[../b:key/text()='DeletedMetadata']"), l != null) for (o = 0; o < l.childNodes.length; o++) for (c = l.childNodes[o].firstChild, p[t(c)] = [], y = 0; y < c.nextSibling.childNodes.length; y++) k = t(c.nextSibling.childNodes[y]), p[t(c)].push(k); d = new SDK.Metadata.Query.RetrieveMetadataChangesResponse(b, nt, p), u(d, e) } else f(v(n)) } function v(n) { var l, u, h, c, e, i, s, o, f, v; if (n.status == 12029) return new Error("The attempt to connect to the server failed."); if (n.status == 12007) return new Error("The server name could not be resolved."); if (l = n.responseXML, u = "Unknown (unable to parse the fault)", typeof l == "object") { var r = null, a = null, y = l.firstChild.firstChild; for (h = 0; h < y.childNodes.length; h++) if (c = y.childNodes[h], "s:Fault" == c.nodeName) { for (e = 0; e < c.childNodes.length; e++) if (i = c.childNodes[e], "faultstring" == i.nodeName && (r = t(i)), "detail" == i.nodeName) for (s = 0; s < i.childNodes.length; s++) if (o = i.childNodes[s], "OrganizationServiceFault" == o.nodeName) for (f = 0; f < o.childNodes.length; f++) if (v = o.childNodes[f], "ErrorCode" == v.nodeName) { a = t(v); break } break } } return (a != null && r != null ? u = "Error Code:" + a + " Message: " + r : r != null && (u = r), u.indexOf("-2147204270") != -1) ? new Error("ExpiredVersionStamp: The clientVersionStamp value passed with the request is before the time specified in the Organization.ExpireSubscriptionsInDays value. Reinitialize your metadata cache using a null clientVersionStamp parameter.") : new Error(u) } function l(n) { for (var t = 0; t < e.length; t++) if (n == e[t]) return !0; return !1 } function r(t) { var s, e, o, f, u, i; if (t.attributes != null && t.attributes.length == 1 && t.attributes.getNamedItem("i:nil") != null && t.attributes.getNamedItem("i:nil").nodeValue == "true") return null; if (t.firstChild != null && t.firstChild.nodeType == 3) { s = n(t); switch (s) { case "ActivityTypeMask": case "ObjectTypeCode": case "ColumnNumber": case "DefaultFormValue": case "MaxValue": case "MinValue": case "MaxLength": case "Order": case "Precision": case "PrecisionSource": case "LanguageCode": return parseInt(t.firstChild.nodeValue, 10); case "AutoRouteToOwnerQueue": case "CanBeChanged": case "CanTriggerWorkflow": case "IsActivity": case "IsActivityParty": case "IsAvailableOffline": case "IsChildEntity": case "IsCustomEntity": case "IsCustomOptionSet": case "IsDocumentManagementEnabled": case "IsEnabledForCharts": case "IsGlobal": case "IsImportable": case "IsIntersect": case "IsManaged": case "IsReadingPaneEnabled": case "IsValidForAdvancedFind": case "CanBeSecuredForCreate": case "CanBeSecuredForRead": case "CanBeSecuredForUpdate": case "IsCustomAttribute": case "IsManaged": case "IsPrimaryId": case "IsPrimaryName": case "IsSecured": case "IsValidForCreate": case "IsValidForRead": case "IsValidForUpdate": case "IsCustomRelationship": case "CanBeBasic": case "CanBeDeep": case "CanBeGlobal": case "CanBeLocal": return t.firstChild.nodeValue == "true" ? !0 : !1; case "Value": return t.firstChild.nodeValue == "true" || t.firstChild.nodeValue == "false" ? t.firstChild.nodeValue == "true" ? !0 : !1 : t.firstChild.nodeValue == "ApplicationRequired" || t.firstChild.nodeValue == "None" || t.firstChild.nodeValue == "Recommended" || t.firstChild.nodeValue == "SystemRequired" ? t.firstChild.nodeValue : parseInt(t.firstChild.nodeValue, 10); default: return t.firstChild.nodeValue } } if (l(n(t))) { for (e = [], i = 0; i < t.childNodes.length; i++) o = t.childNodes[i].attributes != null && t.childNodes[i].attributes.getNamedItem("i:type") != null ? t.childNodes[i].attributes.getNamedItem("i:type").nodeValue.split(":")[1] : n(t.childNodes[i]), f = r(t.childNodes[i]), f._type = o, e.push(f); return e } if (t.childNodes.length == 0) return null; for (u = {}, t.attributes.getNamedItem("i:type") != null && (u._type = t.attributes.getNamedItem("i:type").nodeValue.split(":")[1]), i = 0; i < t.childNodes.length; i++) u[n(t.childNodes[i])] = t.childNodes[i].nodeType == 3 ? t.childNodes[i].nodeValue : r(t.childNodes[i]); return u } function i(n, t) { if (window.ActiveXObject && typeof n.selectSingleNode != "undefined") return n.selectSingleNode(t); var r = new XPathEvaluator, i = r.evaluate(t, n, f, XPathResult.FIRST_ORDERED_NODE_TYPE, null); return i != null ? i.singleNodeValue : null } function a(n, t) { var r = i(n, t); return c(r) ? null : typeof r.text != "undefined" ? r.text : r.textContent } function t(n) { return typeof n.text != "undefined" ? n.text : n.textContent } function c(n) { return n == null ? !0 : n.attributes.getNamedItem("i:nil") != null && n.attributes.getNamedItem("i:nil").value == "true" ? !0 : !1 } function n(n) { return typeof n.baseName != "undefined" ? n.baseName : n.localName } function s(n) { var t = ["xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'", "xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts'", "xmlns:i='http://www.w3.org/2001/XMLSchema-instance'", "xmlns:b='http://schemas.datacontract.org/2004/07/System.Collections.Generic'", "xmlns:c='http://schemas.microsoft.com/xrm/2011/Metadata'"]; n.setProperty("SelectionNamespaces", t.join(" ")) } function f(n) { var t = { s: "http://schemas.xmlsoap.org/soap/envelope/", a: "http://schemas.microsoft.com/xrm/2011/Contracts", i: "http://www.w3.org/2001/XMLSchema-instance", b: "http://schemas.datacontract.org/2004/07/System.Collections.Generic", c: "http://schemas.microsoft.com/xrm/2011/Metadata" }; return t[n] || null } this.AttributeQueryExpression = function (n, t) { function u(n) { try { i.setCriteria(n) } catch (t) { throw t; } } function f(n) { try { i.setProperties(n) } catch (t) { throw t; } } if (!(this instanceof SDK.Metadata.Query.AttributeQueryExpression)) return new SDK.Metadata.Query.AttributeQueryExpression(n, t); var i = null, e = "SDK.Metadata.Query.AttributeQueryExpression is not initialized.", o = "SDK.Metadata.Query.AttributeQueryExpression criteria must be an SDK.Metadata.Query.MetadataFilterExpression", s = "SDK.Metadata.Query.AttributeQueryExpression properties must be an SDK.Metadata.Query.MetadataPropertiesExpression", r = "SDK.Metadata.Query.AttributeQueryExpression criteria and properties parameter values are required."; if (typeof n == "undefined" || typeof t == "undefined" || n == null || t == null) throw new Error(r); else { if (!(n instanceof SDK.Metadata.Query.MetadataFilterExpression)) throw new Error(o); if (!(t instanceof SDK.Metadata.Query.MetadataPropertiesExpression)) throw new Error(s); i = new SDK.Metadata.Query.MetadataQueryExpression(n, t) } this.getCriteria = function () { return i.getCriteria() }, this.setCriteria = function (n) { u(n) }, this.getProperties = function () { return i.getProperties() }, this.setProperties = function (n) { f(n) }, this._toXml = function () { if (i == null) throw new Error(e); return ["<c:AttributeQuery>", i._toXml(), "</c:AttributeQuery>"].join("") } }, this.AttributeQueryExpression.__class = !0, this.Collection = function (n, t) { if (!(this instanceof SDK.Metadata.Query.Collection)) return new SDK.Metadata.Query.Collection(n, t); var r = n, u = "The value being added to the SDK.Metadata.Query.Collection is not the expected type.", i = []; this.count = 0, this.add = function (n) { if (r == String && (n = new String(n)), r == Number && (n = new Number(n)), n instanceof r) i.push(n), this.count++; else throw new Error(u); }, this.clear = function () { i.length = 0, this.Count = 0 }, this.remove = function (n) { for (var t = 0; t < i.length; t++) if (n === i[t]) { i.splice(t, 1), this.count--; return } throw new Error("Item '" + n.toString() + "' not found."); }, this.contains = function (n) { for (var t = 0; t < i.length; t++) if (n === i[t]) return !0; return !1 }, this.addRange = function (n) { var i = "SDK.Metadata.Query.Collection.addRange requires an array parameter.", t; if (n != null) if (typeof n.push != "undefined") for (t = 0; t < n.length; t++) this.add(n[t]); else throw new Error(i); else throw new Error(i); }, this.forEach = function (n) { for (var t = 0; t < i.length; t++) n(i[t], t) }, t != null && this.addRange(t) }, this.Collection.__class = !0, this.EntityQueryExpression = function (n, t, i, r, u) { function v(n) { try { f.setCriteria(n) } catch (t) { throw t; } } function y(n) { try { f.setProperties(n) } catch (t) { throw t; } } function c(n) { if (n == null) s = n; else if (n instanceof SDK.Metadata.Query.AttributeQueryExpression) s = n; else throw new Error(p); } function l(n) { if (n == null) o = n; else if (n instanceof SDK.Metadata.Query.RelationshipQueryExpression) o = n; else throw new Error(b); } function h(n) { if (n == null) e = n; else if (n instanceof SDK.Metadata.Query.LabelQueryExpression) e = n; else throw new Error(k); } if (!(this instanceof SDK.Metadata.Query.EntityQueryExpression)) return new SDK.Metadata.Query.EntityQueryExpression(n, t, i, r, u); var f = null, s = null, o = null, e = null, a = "SDK.Metadata.Query.EntityQueryExpression is not initialized.", g = "SDK.Metadata.Query.EntityQueryExpression criteria must be an SDK.Metadata.Query.MetadataFilterExpression", nt = "SDK.Metadata.Query.EntityQueryExpression properties must be an SDK.Metadata.Query.MetadataPropertiesExpression", p = "SDK.Metadata.Query.EntityQueryExpression attributeQuery must be an SDK.Metadata.Query.AttributeQueryExpression", k = "SDK.Metadata.Query.EntityQueryExpression labelQuery must be an SDK.Metadata.Query.LabelQueryExpression", b = "SDK.Metadata.Query.EntityQueryExpression relationshipQuery must be an SDK.Metadata.Query.RelationshipQueryExpression", w = "SDK.Metadata.Query.EntityQueryExpression criteria and properties parameter values are required."; if (typeof n == "undefined" || typeof t == "undefined" || n == null || t == null) throw new Error(w); else try { f = new SDK.Metadata.Query.MetadataQueryExpression(n, t) } catch (d) { throw d; } typeof i != "undefined" && c(i), typeof r != "undefined" && l(r), typeof u != "undefined" && h(u), this.getCriteria = function () { return f.getCriteria() }, this.setCriteria = function (n) { v(n) }, this.getProperties = function () { return f.getProperties() }, this.setProperties = function (n) { y(n) }, this.getAttributeQuery = function () { return s }, this.setAttributeQuery = function (n) { c(n) }, this.getRelationshipQuery = function () { return o }, this.setRelationshipQuery = function (n) { l(n) }, this.getLabelQuery = function () { return e }, this.setLabelQuery = function (n) { h(n) }, this._toXml = function () { var i, t, n; if (f == null) throw new Error(a); return i = '<c:AttributeQuery i:nil="true" />', s != null && (i = s._toXml()), t = '<c:LabelQuery i:nil="true" />', e != null && (t = e._toXml()), n = '<c:RelationshipQuery i:nil="true" />', o != null && (n = o._toXml()), ['<b:value i:type="c:EntityQueryExpression" xmlns:c="http://schemas.microsoft.com/xrm/2011/Metadata/Query">', f._toXml(), i, t, n, "</b:value>"].join("") } }, this.EntityQueryExpression.__class = !0, this.GuidValue = function (n) { if (!(this instanceof SDK.Metadata.Query.GuidValue)) return new SDK.Metadata.Query.GuidValue(n); var t = null; if (/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(n)) t = n; else throw new Error("Value passed as a Guid Value is not a valid Guid."); this.value = t }, this.GuidValue.__class = !0, this.LabelQueryExpression = function (n) { if (!(this instanceof SDK.Metadata.Query.LabelQueryExpression)) return new SDK.Metadata.Query.LabelQueryExpression(n); var t = null, r; if (typeof n != "undefined") try { t = new SDK.Metadata.Query.Collection(Number, n) } catch (i) { throw i; } else t = new SDK.Metadata.Query.Collection(Number); this.filterLanguages = t, this._toXml = function () { if (t == null) throw new Error("SDK.Metadata.Query.LabelQueryExpression is not initialized."); var n = []; return t.forEach(function (t) { n.push("<d:int>" + t + "</d:int>") }), ['<c:FilterLanguages xmlns:d="http://schemas.microsoft.com/2003/10/Serialization/Arrays">', n.join(""), "</c:FilterLanguages>"].join("") } }, this.LabelQueryExpression.__class = !0, this.MetadataConditionExpression = function (n, t, i) { function l(n) { var o, l, t, i; if (f == null) throw new Error(k); for (o = !1, l = ["AttributeType", "RelationshipType", "OwnershipType", "RequiredLevel", "Format", "ImeMode", "SecurityTypes"], t = 0; t < l.length; t++) if (f == l[t]) { o = !0, e = h.Metadata; break } if (o) switch (f) { case "AttributeType": r = "AttributeTypeCode"; break; case "RelationshipType": r = "RelationshipType"; break; case "OwnershipType": r = "OwnershipTypes"; break; case "RequiredLevel": r = "AttributeRequiredLevel"; break; case "Format": var c = !1, a = !1, v = !1; for (t in SDK.Metadata.Query.ValueEnums.DateTimeFormat) if (u == t) { r = "DateTimeFormat", c = !0; break } if (!c) for (t in SDK.Metadata.Query.ValueEnums.IntegerFormat) if (u == t) { a = !0, r = "IntegerFormat"; break } if (!c && !a) for (t in SDK.Metadata.Query.ValueEnums.StringFormat) if (u == t) { v = !0, r = "StringFormat"; break } if (!c && !a && !v) throw new Error("Unexpected attribute Format metadata enumeration."); break; case "ImeMode": r = "ImeMode"; break; case "SecurityTypes": r = "SecurityTypes" } else (typeof n == "string" || typeof n == "number" || typeof n == "boolean") && (r = typeof n == "number" ? "int" : typeof n); if (s = typeof n == "object" && typeof n.push == "function", s && !o) if (e = h.Arrays, n.length > 0) if (i = typeof n[0], i == "string" || i == "number" || i == "boolean") r = i == "number" ? "int" : i; else throw new Error("Cannot determine the type of items in an array passed as a value to a SDK.Metadata.Query.MetadataConditionExpression."); else throw new Error(y); s || o || (e = h.XMLSchema) } function c(n) { if (typeof n == "string") f = n, u != null && l(u); else throw new Error(p); } function b(n) { for (var t in SDK.Metadata.Query.MetadataConditionOperator) if (n == t) return !0; return !1 } function v(n) { if (n == null) o = n; else if (b(n)) o = n; else throw new Error(d); } function a(n) { if (n == null) u = null, r = "null"; else if (n instanceof SDK.Metadata.Query.GuidValue) u = n.value, r = "guid", e = h.Serialization; else { if (typeof n == "undefined" || n == null || typeof n != "string" && typeof n != "number" && typeof n != "boolean" && typeof n != "object" || typeof n == "object" && typeof n.push == "undefined" || typeof n == "object" && typeof n.push == "function" && n.length == 0) throw new Error(y); l(n), u = n } } if (!(this instanceof SDK.Metadata.Query.MetadataConditionExpression)) return new SDK.Metadata.Query.MetadataConditionExpression(n, t, i); var o = null, f = null, u = null, r = null, s = !1, h = { Serialization: '"http://schemas.microsoft.com/2003/10/Serialization/"', Arrays: '"http://schemas.microsoft.com/2003/10/Serialization/Arrays"', Metadata: '"http://schemas.microsoft.com/xrm/2011/Metadata"', XMLSchema: '"http://www.w3.org/2001/XMLSchema"' }, e = null, w = "A SDK.Metadata.Query.MetadataConditionExpression has properties that are null.", p = "The propertyName parameter value must be a string.", d = "The conditionOperator parameter value must be an SDK.Metadata.Query.MetadataConditionOperator", y = "The value parameter must be either an array, a string, a number, a boolean value, or null. If an array, it must have at least one item.", k = "The MetadataConditionExpression property name must be known to validate the MetadataConditionExpression value."; typeof n != undefined && c(n), typeof t != undefined && v(t), typeof i != undefined && a(i), this.getConditionOperator = function () { return o }, this.setConditionOperator = function (n) { v(n) }, this.getPropertyName = function () { return f }, this.setPropertyName = function (n) { c(n) }, this.getValue = function () { return u }, this.setValue = function (n) { a(n) }, this._toXml = function () { var n, t; if (o == null || f == null || r == null) throw new Error(w); if (r == "null") n = '<c:Value i:nil="true" />'; else if (s) { for (n = '<c:Value i:type="d:ArrayOf' + r + '" xmlns:d=' + e + ">", t = 0; t < u.length; t++) n += "<d:" + r + ">" + u[t] + "</d:" + r + ">"; n += "</c:Value>" } else n = '<c:Value i:type="d:' + r + '" xmlns:d=' + e + ">" + u + "</c:Value>"; return ["<c:MetadataConditionExpression>", "<c:ConditionOperator>" + o + "</c:ConditionOperator>", "<c:PropertyName>" + f + "</c:PropertyName>", n, "</c:MetadataConditionExpression>"].join("") } }, this.MetadataConditionExpression.__class = !0, this.MetadataFilterExpression = function (n) { function s() { var u = [], n; return t.forEach(function (n) { u.push(n._toXml()) }), n = [], i.forEach(function (t) { n.push("<c:MetadataFilterExpression>"), n.push(t._toXml()), n.push("</c:MetadataFilterExpression>") }), ["<c:Conditions>", u.join(""), "</c:Conditions>", "<c:FilterOperator>" + r + "</c:FilterOperator>", "<c:Filters>", n.join(""), "</c:Filters>", ].join("") } function f(n) { if (n instanceof SDK.Metadata.Query.MetadataConditionExpressionCollection) t = n; else throw new Error(o); } function u(n) { if (n != null && (n == "Or" || n == "And")) r = n; else throw new Error(e); } if (!(this instanceof SDK.Metadata.Query.MetadataFilterExpression)) return new SDK.Metadata.Query.MetadataFilterExpression(n); var r = SDK.Metadata.Query.LogicalOperator.And, t = new SDK.Metadata.Query.Collection(SDK.Metadata.Query.MetadataConditionExpression), i = new SDK.Metadata.Query.Collection(SDK.Metadata.Query.MetadataFilterExpression), e = "SDK.Metadata.Query.MetadataFilterExpression FilterOperator requires a SDK.Metadata.Query.LogicalOperator.", o = "SDK.Metadata.Query.MetadataFilterExpression Conditions requires a SDK.Metadata.Query.MetadataConditionExpressionCollection."; typeof n != "undefined" && u(n), this.addCondition = function (n, i, r) { n instanceof SDK.Metadata.Query.MetadataConditionExpression && i == null && r == null ? t.add(n) : t.add(new SDK.Metadata.Query.MetadataConditionExpression(n, i, r)) }, this.addConditions = function (n) { t.addRange(n) }, this.addFilter = function (n) { if (!(n instanceof SDK.Metadata.Query.MetadataFilterExpression)) throw new Error("addFilter filter parameter requires a SDK.Metadata.Query.MetadataFilterExpression)"); i.add(n) }, this.getConditions = function () { return t }, this.setConditions = function (n) { f(n) }, this.getFilterOperator = function () { return r }, this.setFilterOperator = function (n) { u(n) }, this.getFilters = function () { return i }, this._toXml = s }, this.MetadataFilterExpression.__class = !0, this.MetadataPropertiesExpression = function (n, t) { function u(n) { if (typeof n == "boolean") r = n; else throw new Error(o); } function f(n) { if (typeof n.push != "undefined") i = new SDK.Metadata.Query.Collection(String, n); else throw new Error(e); } if (!(this instanceof SDK.Metadata.Query.MetadataPropertiesExpression)) return new SDK.Metadata.Query.MetadataPropertiesExpression(n, t); var r = n, i = new SDK.Metadata.Query.Collection(String), o = "The SDK.Metadata.Query.MetadataPropertiesExpression allProperties  must be an Boolean value.", e = "The SDK.Metadata.Query.MetadataPropertiesExpression propertyNames  must be an Array."; typeof n != "undefined" && u(n), typeof t != "undefined" && f(t), this.addProperty = function (n) { i.add(n) }, this.addProperties = function (n) { i.addRange(n) }, this.getAllProperties = function () { return r }, this.setAllProperties = function (n) { u(n) }, this.getPropertyNames = function () { return i }, this.setPropertyNames = function (n) { f(n) }, this._toXml = function () { var n = []; return i.forEach(function (t) { n.push("<d:string>" + t + "</d:string>") }), ["<c:AllProperties>" + r + "</c:AllProperties>", '<c:PropertyNames xmlns:d="http://schemas.microsoft.com/2003/10/Serialization/Arrays">', n.join(""), "</c:PropertyNames>"].join("") } }, this.MetadataPropertiesExpression.__class = !0, this.MetadataQueryExpression = function (n, t) { function u(n) { if (n == null) r = n; else if (n instanceof SDK.Metadata.Query.MetadataFilterExpression) r = n; else throw new Error(h); } function f(n) { if (n == null) i = n; else if (n instanceof SDK.Metadata.Query.MetadataPropertiesExpression) i = n; else throw new Error(o); } if (!(this instanceof SDK.Metadata.Query.MetadataQueryExpression)) return new SDK.Metadata.Query.MetadataQueryExpression(n, t); var r = null, i = null, e = "SDK.Metadata.Query.MetadataQueryExpression criteria  is null.", s = "SDK.Metadata.Query.MetadataQueryExpression properties  is null.", h = "SDK.Metadata.Query.MetadataQueryExpression criteria  must be an SDK.Metadata.Query.MetadataFilterExpression", o = "SDK.Metadata.Query.MetadataQueryExpression properties  must be an SDK.Metadata.Query.MetadataPropertiesExpression"; u(n), f(t), this.getCriteria = function () { return r }, this.setCriteria = function (n) { u(n) }, this.getProperties = function () { return i }, this.setProperties = function (n) { f(n) }, this._toXml = function () { if (r == null) throw new Error(e); if (i == null) throw new Error(s); return ["<c:Criteria>", r._toXml(), "</c:Criteria>", "<c:Properties>", i._toXml(), "</c:Properties>"].join("") } }, this.MetadataQueryExpression.__class = !0, this.RelationshipQueryExpression = function (n, t) { function u(n) { try { i.setCriteria(n) } catch (t) { throw t; } } function f(n) { try { i.setProperties(n) } catch (t) { throw t; } } if (!(this instanceof SDK.Metadata.Query.RelationshipQueryExpression)) return new SDK.Metadata.Query.RelationshipQueryExpression(n, t); var i = null, e = "SDK.Metadata.Query.RelationshipQueryExpression is not initialized.", o = "SDK.Metadata.Query.RelationshipQueryExpression criteria must be an SDK.Metadata.Query.MetadataFilterExpression", s = "SDK.Metadata.Query.RelationshipQueryExpression properties must be an SDK.Metadata.Query.MetadataPropertiesExpression", r = "SDK.Metadata.Query.RelationshipQueryExpression criteria and properties parameter values are required."; if (typeof n == "undefined" || typeof t == "undefined" || n == null || t == null) throw new Error(r); else { if (!(n instanceof SDK.Metadata.Query.MetadataFilterExpression)) throw new Error(o); if (!(t instanceof SDK.Metadata.Query.MetadataPropertiesExpression)) throw new Error(s); i = new SDK.Metadata.Query.MetadataQueryExpression(n, t) } this.getCriteria = function () { return i.getCriteria() }, this.setCriteria = function (n) { u(n) }, this.getProperties = function () { return i.getProperties() }, this.setProperties = function (n) { f(n) }, this._toXml = function () { if (i == null) throw new Error(e); return ["<c:RelationshipQuery>", i._toXml(), "</c:RelationshipQuery>"].join("") } }, this.RelationshipQueryExpression.__class = !0, this.DeletedMetadataFilters = function () { throw new Error("Constructor not implemented this is a static enum."); }, this.MetadataConditionOperator = function () { throw new Error("Constructor not implemented this is a static enum."); }, this.LogicalOperator = function () { throw new Error("Constructor not implemented this is a static enum."); }, this.SearchableEntityMetadataProperties = function () { throw new Error("Constructor not implemented this is a static enum."); }, this.SearchableAttributeMetadataProperties = function () { throw new Error("Constructor not implemented this is a static enum."); }, this.SearchableRelationshipMetadataProperties = function () { throw new Error("Constructor not implemented this is a static enum."); }, this.EntityMetadataProperties = function () { throw new Error("Constructor not implemented this is a static enum."); }, this.AttributeMetadataProperties = function () { throw new Error("Constructor not implemented this is a static enum."); }, this.RelationshipMetadataProperties = function () { throw new Error("Constructor not implemented this is a static enum."); }, this.RetrieveMetadataChangesRequest = function (n, t, i) { function e(n) { if (n == null) f = n; else if (n instanceof SDK.Metadata.Query.EntityQueryExpression) f = n; else throw new Error(c); } function o(n) { if (n == null) u = n; else if (typeof n == "string") u = n; else throw new Error(l); } function s(n) { if (n == null) r = n; else if (n >= 1 && n <= 31) r = n; else throw new Error(a); } if (!(this instanceof SDK.Metadata.Query.RetrieveMetadataChangesRequest)) return new SDK.Metadata.Query.RetrieveMetadataChangesRequest(n, t, i); var f = null, u = null, r = null, h = "SDK.Metadata.Query.RetrieveMetadataChangesRequest Query is null.", c = "SDK.Metadata.Query.RetrieveMetadataChangesRequest.Query requires a SDK.Metadata.Query.EntityQueryExpression.", l = "SDK.Metadata.Query.RetrieveMetadataChangesRequest ClientVersionStamp requires a string value.", a = "SDK.Metadata.Query.RetrieveMetadataChangesRequest DeletedMetadataFilters must be between 1 and 31."; e(n), o(t), s(i), this.getQuery = function () { return f }, this.setQuery = function (n) { e(n) }, this.getClientVersionStamp = function () { return u }, this.setClientVersionStamp = function (n) { o(n) }, this.getDeletedMetadataFilters = function () { return r }, this.setDeletedMetadataFilters = function (n) { s(n) }, this._toXml = function () { var i, e, n, t; if (f == null) throw new Error(h); return i = "", u != null && (i = ["<a:KeyValuePairOfstringanyType>", "<b:key>ClientVersionStamp</b:key>", '<b:value i:type="c:string" xmlns:c="http://www.w3.org/2001/XMLSchema">' + u + "</b:value>", "</a:KeyValuePairOfstringanyType>"].join("")), e = "Entity", r != null && (n = [], (1 & r) == 1 && n.push("Entity"), (2 & r) == 2 && n.push("Attribute"), (4 & r) == 4 && n.push("Relationship"), (8 & r) == 8 && n.push("Label"), (16 & r) == 16 && n.push("OptionSet"), e = n.join(" ")), t = "", u != null && r != null && (t = ["<a:KeyValuePairOfstringanyType>", "<b:key>DeletedMetadataFilters</b:key>", '<b:value i:type="c:DeletedMetadataFilters"', ' xmlns:c="http://schemas.microsoft.com/xrm/2011/Metadata/Query">' + e + "</b:value>", "</a:KeyValuePairOfstringanyType>"].join("")), ['<request i:type="a:RetrieveMetadataChangesRequest" xmlns:a="http://schemas.microsoft.com/xrm/2011/Contracts">', '<a:Parameters xmlns:b="http://schemas.datacontract.org/2004/07/System.Collections.Generic">', "<a:KeyValuePairOfstringanyType>", "<b:key>Query</b:key>", f._toXml(), "</a:KeyValuePairOfstringanyType>", i, t, "</a:Parameters>", '<a:RequestId i:nil="true" />', "<a:RequestName>RetrieveMetadataChanges</a:RequestName>", "</request>"].join("") } }, this.RetrieveMetadataChangesResponse = function (n, t, i) { if (!(this instanceof SDK.Metadata.Query.RetrieveMetadataChangesResponse)) return new SDK.Metadata.Query.RetrieveMetadataChangesResponse(n, t, i); var f = null, u = null, r = null; typeof n != "undefined" && (f = n), typeof u != "undefined" && (u = t), typeof r != "undefined" && (r = i), this.EntityMetadata = f, this.ServerVersionStamp = u, this.DeletedMetadata = r }, this.RetrieveMetadataChanges = function (n, t, i, r) { if (!(n instanceof SDK.Metadata.Query.RetrieveMetadataChangesRequest)) throw new Error("SDK.Metadata.Query.RetrieveMetadataChanges RetrieveMetadataChangesRequest parameter must be an SDK.Metadata.Query.RetrieveMetadataChangesRequest."); if (typeof t != "function") throw new Error("SDK.Metadata.Query.RetrieveMetadataChanges successCallBack parameter must be a function."); if (typeof i != "function") throw new Error("SDK.Metadata.Query.RetrieveMetadataChanges errorCallBack parameter must be a function."); var f = ['<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body>', '<Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">', n._toXml(), "</Execute></s:Body></s:Envelope>"].join(""), u = new XMLHttpRequest; u.open("POST", h() + "/XRMServices/2011/Organization.svc/web", !0); try { u.responseType = "msxml-document" } catch (e) { } u.setRequestHeader("Accept", "application/xml, text/xml, */*"), u.setRequestHeader("Content-Type", "text/xml; charset=utf-8"), u.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute"), u.onreadystatechange = function () { o(u, t, i, r) }, u.send(f) }; var e = ["Attributes", "ManyToManyRelationships", "ManyToOneRelationships", "OneToManyRelationships", "Privileges", "LocalizedLabels", "Options", "Targets"] }.call(SDK.Metadata.Query), SDK.Metadata.Query.LogicalOperator.prototype = { And: "And", Or: "Or" }, SDK.Metadata.Query.LogicalOperator.And = "And", SDK.Metadata.Query.LogicalOperator.Or = "Or", SDK.Metadata.Query.LogicalOperator.__enum = !0, SDK.Metadata.Query.LogicalOperator.__flags = !0, SDK.Metadata.Query.DeletedMetadataFilters.prototype = { Default: 1, Entity: 1, Attribute: 2, Relationship: 4, Label: 8, OptionSet: 16, All: 31 }, SDK.Metadata.Query.DeletedMetadataFilters.Default = 1, SDK.Metadata.Query.DeletedMetadataFilters.Entity = 1, SDK.Metadata.Query.DeletedMetadataFilters.Attribute = 2, SDK.Metadata.Query.DeletedMetadataFilters.Relationship = 4, SDK.Metadata.Query.DeletedMetadataFilters.Label = 8, SDK.Metadata.Query.DeletedMetadataFilters.OptionSet = 16, SDK.Metadata.Query.DeletedMetadataFilters.All = 31, SDK.Metadata.Query.DeletedMetadataFilters.__enum = !0, SDK.Metadata.Query.DeletedMetadataFilters.__flags = !0, SDK.Metadata.Query.MetadataConditionOperator.prototype = { Equals: "Equals", NotEquals: "NotEquals", In: "In", NotIn: "NotIn", GreaterThan: "GreaterThan", LessThan: "LessThan" }, SDK.Metadata.Query.MetadataConditionOperator.Equals = "Equals", SDK.Metadata.Query.MetadataConditionOperator.NotEquals = "NotEquals", SDK.Metadata.Query.MetadataConditionOperator.In = "In", SDK.Metadata.Query.MetadataConditionOperator.NotIn = "NotIn", SDK.Metadata.Query.MetadataConditionOperator.GreaterThan = "GreaterThan", SDK.Metadata.Query.MetadataConditionOperator.LessThan = "LessThan", SDK.Metadata.Query.MetadataConditionOperator.__enum = !0, SDK.Metadata.Query.MetadataConditionOperator.__flags = !0, SDK.Metadata.Query.SearchableEntityMetadataProperties.prototype = { ActivityTypeMask: "ActivityTypeMask", AutoRouteToOwnerQueue: "AutoRouteToOwnerQueue", CanBeInManyToMany: "CanBeInManyToMany", CanBePrimaryEntityInRelationship: "CanBePrimaryEntityInRelationship", CanBeRelatedEntityInRelationship: "CanBeRelatedEntityInRelationship", CanCreateAttributes: "CanCreateAttributes", CanCreateCharts: "CanCreateCharts", CanCreateForms: "CanCreateForms", CanCreateViews: "CanCreateViews", CanModifyAdditionalSettings: "CanModifyAdditionalSettings", CanTriggerWorkflow: "CanTriggerWorkflow", IconLargeName: "IconLargeName", IconMediumName: "IconMediumName", IconSmallName: "IconSmallName", IsActivity: "IsActivity", IsActivityParty: "IsActivityParty", IsAuditEnabled: "IsAuditEnabled", IsAvailableOffline: "IsAvailableOffline", IsChildEntity: "IsChildEntity", IsConnectionsEnabled: "IsConnectionsEnabled", IsCustomEntity: "IsCustomEntity", IsCustomizable: "IsCustomizable", IsDocumentManagementEnabled: "IsDocumentManagementEnabled", IsDuplicateDetectionEnabled: "IsDuplicateDetectionEnabled", IsEnabledForCharts: "IsEnabledForCharts", IsImportable: "IsImportable", IsIntersect: "IsIntersect", IsMailMergeEnabled: "IsMailMergeEnabled", IsManaged: "IsManaged", IsMappable: "IsMappable", IsReadingPaneEnabled: "IsReadingPaneEnabled", IsRenameable: "IsRenameable", IsValidForAdvancedFind: "IsValidForAdvancedFind", IsValidForQueue: "IsValidForQueue", IsVisibleInMobile: "IsVisibleInMobile", LogicalName: "LogicalName", MetadataId: "MetadataId", ObjectTypeCode: "ObjectTypeCode", OwnershipType: "OwnershipType", PrimaryIdAttribute: "PrimaryIdAttribute", PrimaryNameAttribute: "PrimaryNameAttribute", RecurrenceBaseEntityLogicalName: "RecurrenceBaseEntityLogicalName", ReportViewName: "ReportViewName", SchemaName: "SchemaName" }, SDK.Metadata.Query.SearchableEntityMetadataProperties.ActivityTypeMask = "ActivityTypeMask", SDK.Metadata.Query.SearchableEntityMetadataProperties.AutoRouteToOwnerQueue = "AutoRouteToOwnerQueue", SDK.Metadata.Query.SearchableEntityMetadataProperties.CanBeInManyToMany = "CanBeInManyToMany", SDK.Metadata.Query.SearchableEntityMetadataProperties.CanBePrimaryEntityInRelationship = "CanBePrimaryEntityInRelationship", SDK.Metadata.Query.SearchableEntityMetadataProperties.CanBeRelatedEntityInRelationship = "CanBeRelatedEntityInRelationship", SDK.Metadata.Query.SearchableEntityMetadataProperties.CanCreateAttributes = "CanCreateAttributes", SDK.Metadata.Query.SearchableEntityMetadataProperties.CanCreateCharts = "CanCreateCharts", SDK.Metadata.Query.SearchableEntityMetadataProperties.CanCreateForms = "CanCreateForms", SDK.Metadata.Query.SearchableEntityMetadataProperties.CanCreateViews = "CanCreateViews", SDK.Metadata.Query.SearchableEntityMetadataProperties.CanModifyAdditionalSettings = "CanModifyAdditionalSettings", SDK.Metadata.Query.SearchableEntityMetadataProperties.CanTriggerWorkflow = "CanTriggerWorkflow", SDK.Metadata.Query.SearchableEntityMetadataProperties.IconLargeName = "IconLargeName", SDK.Metadata.Query.SearchableEntityMetadataProperties.IconMediumName = "IconMediumName", SDK.Metadata.Query.SearchableEntityMetadataProperties.IconSmallName = "IconSmallName", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsActivity = "IsActivity", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsActivityParty = "IsActivityParty", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsAuditEnabled = "IsAuditEnabled", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsAvailableOffline = "IsAvailableOffline", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsChildEntity = "IsChildEntity", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsConnectionsEnabled = "IsConnectionsEnabled", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsCustomEntity = "IsCustomEntity", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsCustomizable = "IsCustomizable", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsDocumentManagementEnabled = "IsDocumentManagementEnabled", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsDuplicateDetectionEnabled = "IsDuplicateDetectionEnabled", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsEnabledForCharts = "IsEnabledForCharts", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsImportable = "IsImportable", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsIntersect = "IsIntersect", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsMailMergeEnabled = "IsMailMergeEnabled", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsManaged = "IsManaged", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsMappable = "IsMappable", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsReadingPaneEnabled = "IsReadingPaneEnabled", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsRenameable = "IsRenameable", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsValidForAdvancedFind = "IsValidForAdvancedFind", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsValidForQueue = "IsValidForQueue", SDK.Metadata.Query.SearchableEntityMetadataProperties.IsVisibleInMobile = "IsVisibleInMobile", SDK.Metadata.Query.SearchableEntityMetadataProperties.LogicalName = "LogicalName", SDK.Metadata.Query.SearchableEntityMetadataProperties.MetadataId = "MetadataId", SDK.Metadata.Query.SearchableEntityMetadataProperties.ObjectTypeCode = "ObjectTypeCode", SDK.Metadata.Query.SearchableEntityMetadataProperties.OwnershipType = "OwnershipType", SDK.Metadata.Query.SearchableEntityMetadataProperties.PrimaryIdAttribute = "PrimaryIdAttribute", SDK.Metadata.Query.SearchableEntityMetadataProperties.PrimaryNameAttribute = "PrimaryNameAttribute", SDK.Metadata.Query.SearchableEntityMetadataProperties.RecurrenceBaseEntityLogicalName = "RecurrenceBaseEntityLogicalName", SDK.Metadata.Query.SearchableEntityMetadataProperties.ReportViewName = "ReportViewName", SDK.Metadata.Query.SearchableEntityMetadataProperties.SchemaName = "SchemaName", SDK.Metadata.Query.SearchableEntityMetadataProperties.__enum = !0, SDK.Metadata.Query.SearchableEntityMetadataProperties.__flags = !0, SDK.Metadata.Query.SearchableAttributeMetadataProperties.prototype = { AttributeOf: "AttributeOf", AttributeType: "AttributeType", CalculationOf: "CalculationOf", CanBeSecuredForCreate: "CanBeSecuredForCreate", CanBeSecuredForRead: "CanBeSecuredForRead", CanBeSecuredForUpdate: "CanBeSecuredForUpdate", CanModifyAdditionalSettings: "CanModifyAdditionalSettings", ColumnNumber: "ColumnNumber", DefaultFormValue: "DefaultFormValue", DefaultValue: "DefaultValue", DeprecatedVersion: "DeprecatedVersion", EntityLogicalName: "EntityLogicalName", Format: "Format", ImeMode: "ImeMode", IsAuditEnabled: "IsAuditEnabled", IsCustomAttribute: "IsCustomAttribute", IsCustomizable: "IsCustomizable", IsManaged: "IsManaged", IsPrimaryId: "IsPrimaryId", IsPrimaryName: "IsPrimaryName", IsRenameable: "IsRenameable", IsSecured: "IsSecured", IsValidForAdvancedFind: "IsValidForAdvancedFind", IsValidForCreate: "IsValidForCreate", IsValidForRead: "IsValidForRead", IsValidForUpdate: "IsValidForUpdate", LinkedAttributeId: "LinkedAttributeId", LogicalName: "LogicalName", MaxLength: "MaxLength", MaxValue: "MaxValue", MetadataId: "MetadataId", MinValue: "MinValue", Precision: "Precision", PrecisionSource: "PrecisionSource", RequiredLevel: "RequiredLevel", SchemaName: "SchemaName", YomiOf: "YomiOf" }, SDK.Metadata.Query.SearchableAttributeMetadataProperties.AttributeOf = "AttributeOf", SDK.Metadata.Query.SearchableAttributeMetadataProperties.AttributeType = "AttributeType", SDK.Metadata.Query.SearchableAttributeMetadataProperties.CalculationOf = "CalculationOf", SDK.Metadata.Query.SearchableAttributeMetadataProperties.CanBeSecuredForCreate = "CanBeSecuredForCreate", SDK.Metadata.Query.SearchableAttributeMetadataProperties.CanBeSecuredForRead = "CanBeSecuredForRead", SDK.Metadata.Query.SearchableAttributeMetadataProperties.CanBeSecuredForUpdate = "CanBeSecuredForUpdate", SDK.Metadata.Query.SearchableAttributeMetadataProperties.CanModifyAdditionalSettings = "CanModifyAdditionalSettings", SDK.Metadata.Query.SearchableAttributeMetadataProperties.ColumnNumber = "ColumnNumber", SDK.Metadata.Query.SearchableAttributeMetadataProperties.DefaultFormValue = "DefaultFormValue", SDK.Metadata.Query.SearchableAttributeMetadataProperties.DefaultValue = "DefaultValue", SDK.Metadata.Query.SearchableAttributeMetadataProperties.DeprecatedVersion = "DeprecatedVersion", SDK.Metadata.Query.SearchableAttributeMetadataProperties.EntityLogicalName = "EntityLogicalName", SDK.Metadata.Query.SearchableAttributeMetadataProperties.Format = "Format", SDK.Metadata.Query.SearchableAttributeMetadataProperties.ImeMode = "ImeMode", SDK.Metadata.Query.SearchableAttributeMetadataProperties.IsAuditEnabled = "IsAuditEnabled", SDK.Metadata.Query.SearchableAttributeMetadataProperties.IsCustomAttribute = "IsCustomAttribute", SDK.Metadata.Query.SearchableAttributeMetadataProperties.IsCustomizable = "IsCustomizable", SDK.Metadata.Query.SearchableAttributeMetadataProperties.IsManaged = "IsManaged", SDK.Metadata.Query.SearchableAttributeMetadataProperties.IsPrimaryId = "IsPrimaryId", SDK.Metadata.Query.SearchableAttributeMetadataProperties.IsPrimaryName = "IsPrimaryName", SDK.Metadata.Query.SearchableAttributeMetadataProperties.IsRenameable = "IsRenameable", SDK.Metadata.Query.SearchableAttributeMetadataProperties.IsSecured = "IsSecured", SDK.Metadata.Query.SearchableAttributeMetadataProperties.IsValidForAdvancedFind = "IsValidForAdvancedFind", SDK.Metadata.Query.SearchableAttributeMetadataProperties.IsValidForCreate = "IsValidForCreate", SDK.Metadata.Query.SearchableAttributeMetadataProperties.IsValidForRead = "IsValidForRead", SDK.Metadata.Query.SearchableAttributeMetadataProperties.IsValidForUpdate = "IsValidForUpdate", SDK.Metadata.Query.SearchableAttributeMetadataProperties.LinkedAttributeId = "LinkedAttributeId", SDK.Metadata.Query.SearchableAttributeMetadataProperties.LogicalName = "LogicalName", SDK.Metadata.Query.SearchableAttributeMetadataProperties.MaxLength = "MaxLength", SDK.Metadata.Query.SearchableAttributeMetadataProperties.MaxValue = "MaxValue", SDK.Metadata.Query.SearchableAttributeMetadataProperties.MetadataId = "MetadataId", SDK.Metadata.Query.SearchableAttributeMetadataProperties.MinValue = "MinValue", SDK.Metadata.Query.SearchableAttributeMetadataProperties.Precision = "Precision", SDK.Metadata.Query.SearchableAttributeMetadataProperties.PrecisionSource = "PrecisionSource", SDK.Metadata.Query.SearchableAttributeMetadataProperties.RequiredLevel = "RequiredLevel", SDK.Metadata.Query.SearchableAttributeMetadataProperties.SchemaName = "SchemaName", SDK.Metadata.Query.SearchableAttributeMetadataProperties.YomiOf = "YomiOf", SDK.Metadata.Query.SearchableAttributeMetadataProperties.__enum = !0, SDK.Metadata.Query.SearchableAttributeMetadataProperties.__flags = !0, SDK.Metadata.Query.SearchableRelationshipMetadataProperties.prototype = { Entity1IntersectAttribute: "Entity1IntersectAttribute", Entity1LogicalName: "Entity1LogicalName", Entity2IntersectAttribute: "Entity2IntersectAttribute", Entity2LogicalName: "Entity2LogicalName", IntersectEntityName: "IntersectEntityName", IsCustomizable: "IsCustomizable", IsCustomRelationship: "IsCustomRelationship", IsManaged: "IsManaged", IsValidForAdvancedFind: "IsValidForAdvancedFind", MetadataId: "MetadataId", ReferencedAttribute: "ReferencedAttribute", ReferencedEntity: "ReferencedEntity", ReferencingAttribute: "ReferencingAttribute", ReferencingEntity: "ReferencingEntity", RelationshipType: "RelationshipType", SchemaName: "SchemaName", SecurityTypes: "SecurityTypes" }, SDK.Metadata.Query.SearchableRelationshipMetadataProperties.Entity1IntersectAttribute = "Entity1IntersectAttribute", SDK.Metadata.Query.SearchableRelationshipMetadataProperties.Entity1LogicalName = "Entity1LogicalName", SDK.Metadata.Query.SearchableRelationshipMetadataProperties.Entity2IntersectAttribute = "Entity2IntersectAttribute", SDK.Metadata.Query.SearchableRelationshipMetadataProperties.Entity2LogicalName = "Entity2LogicalName", SDK.Metadata.Query.SearchableRelationshipMetadataProperties.IntersectEntityName = "IntersectEntityName", SDK.Metadata.Query.SearchableRelationshipMetadataProperties.IsCustomizable = "IsCustomizable", SDK.Metadata.Query.SearchableRelationshipMetadataProperties.IsCustomRelationship = "IsCustomRelationship", SDK.Metadata.Query.SearchableRelationshipMetadataProperties.IsManaged = "IsManaged", SDK.Metadata.Query.SearchableRelationshipMetadataProperties.IsValidForAdvancedFind = "IsValidForAdvancedFind", SDK.Metadata.Query.SearchableRelationshipMetadataProperties.MetadataId = "MetadataId", SDK.Metadata.Query.SearchableRelationshipMetadataProperties.ReferencedAttribute = "ReferencedAttribute", SDK.Metadata.Query.SearchableRelationshipMetadataProperties.ReferencedEntity = "ReferencedEntity", SDK.Metadata.Query.SearchableRelationshipMetadataProperties.ReferencingAttribute = "ReferencingAttribute", SDK.Metadata.Query.SearchableRelationshipMetadataProperties.ReferencingEntity = "ReferencingEntity", SDK.Metadata.Query.SearchableRelationshipMetadataProperties.RelationshipType = "RelationshipType", SDK.Metadata.Query.SearchableRelationshipMetadataProperties.SchemaName = "SchemaName", SDK.Metadata.Query.SearchableRelationshipMetadataProperties.SecurityTypes = "SecurityTypes", SDK.Metadata.Query.SearchableRelationshipMetadataProperties.__enum = !0, SDK.Metadata.Query.SearchableRelationshipMetadataProperties.__flags = !0, SDK.Metadata.Query.EntityMetadataProperties.prototype = { ActivityTypeMask: "ActivityTypeMask", Attributes: "Attributes", AutoRouteToOwnerQueue: "AutoRouteToOwnerQueue", CanBeInManyToMany: "CanBeInManyToMany", CanBePrimaryEntityInRelationship: "CanBePrimaryEntityInRelationship", CanBeRelatedEntityInRelationship: "CanBeRelatedEntityInRelationship", CanCreateAttributes: "CanCreateAttributes", CanCreateCharts: "CanCreateCharts", CanCreateForms: "CanCreateForms", CanCreateViews: "CanCreateViews", CanModifyAdditionalSettings: "CanModifyAdditionalSettings", CanTriggerWorkflow: "CanTriggerWorkflow", Description: "Description", DisplayCollectionName: "DisplayCollectionName", DisplayName: "DisplayName", IconLargeName: "IconLargeName", IconMediumName: "IconMediumName", IconSmallName: "IconSmallName", IsActivity: "IsActivity", IsActivityParty: "IsActivityParty", IsAuditEnabled: "IsAuditEnabled", IsAvailableOffline: "IsAvailableOffline", IsChildEntity: "IsChildEntity", IsConnectionsEnabled: "IsConnectionsEnabled", IsCustomEntity: "IsCustomEntity", IsCustomizable: "IsCustomizable", IsDocumentManagementEnabled: "IsDocumentManagementEnabled", IsDuplicateDetectionEnabled: "IsDuplicateDetectionEnabled", IsEnabledForCharts: "IsEnabledForCharts", IsImportable: "IsImportable", IsIntersect: "IsIntersect", IsMailMergeEnabled: "IsMailMergeEnabled", IsManaged: "IsManaged", IsMappable: "IsMappable", IsReadingPaneEnabled: "IsReadingPaneEnabled", IsRenameable: "IsRenameable", IsValidForAdvancedFind: "IsValidForAdvancedFind", IsValidForQueue: "IsValidForQueue", IsVisibleInMobile: "IsVisibleInMobile", LogicalName: "LogicalName", ManyToManyRelationships: "ManyToManyRelationships", ManyToOneRelationships: "ManyToOneRelationships", MetadataId: "MetadataId", ObjectTypeCode: "ObjectTypeCode", OneToManyRelationships: "OneToManyRelationships", OwnershipType: "OwnershipType", PrimaryIdAttribute: "PrimaryIdAttribute", PrimaryNameAttribute: "PrimaryNameAttribute", Privileges: "Privileges", RecurrenceBaseEntityLogicalName: "RecurrenceBaseEntityLogicalName", ReportViewName: "ReportViewName", SchemaName: "SchemaName" }, SDK.Metadata.Query.EntityMetadataProperties.ActivityTypeMask = "ActivityTypeMask", SDK.Metadata.Query.EntityMetadataProperties.Attributes = "Attributes", SDK.Metadata.Query.EntityMetadataProperties.AutoRouteToOwnerQueue = "AutoRouteToOwnerQueue", SDK.Metadata.Query.EntityMetadataProperties.CanBeInManyToMany = "CanBeInManyToMany", SDK.Metadata.Query.EntityMetadataProperties.CanBePrimaryEntityInRelationship = "CanBePrimaryEntityInRelationship", SDK.Metadata.Query.EntityMetadataProperties.CanBeRelatedEntityInRelationship = "CanBeRelatedEntityInRelationship", SDK.Metadata.Query.EntityMetadataProperties.CanCreateAttributes = "CanCreateAttributes", SDK.Metadata.Query.EntityMetadataProperties.CanCreateCharts = "CanCreateCharts", SDK.Metadata.Query.EntityMetadataProperties.CanCreateForms = "CanCreateForms", SDK.Metadata.Query.EntityMetadataProperties.CanCreateViews = "CanCreateViews", SDK.Metadata.Query.EntityMetadataProperties.CanModifyAdditionalSettings = "CanModifyAdditionalSettings", SDK.Metadata.Query.EntityMetadataProperties.CanTriggerWorkflow = "CanTriggerWorkflow", SDK.Metadata.Query.EntityMetadataProperties.Description = "Description", SDK.Metadata.Query.EntityMetadataProperties.DisplayCollectionName = "DisplayCollectionName", SDK.Metadata.Query.EntityMetadataProperties.DisplayName = "DisplayName", SDK.Metadata.Query.EntityMetadataProperties.IconLargeName = "IconLargeName", SDK.Metadata.Query.EntityMetadataProperties.IconMediumName = "IconMediumName", SDK.Metadata.Query.EntityMetadataProperties.IconSmallName = "IconSmallName", SDK.Metadata.Query.EntityMetadataProperties.IsActivity = "IsActivity", SDK.Metadata.Query.EntityMetadataProperties.IsActivityParty = "IsActivityParty", SDK.Metadata.Query.EntityMetadataProperties.IsAuditEnabled = "IsAuditEnabled", SDK.Metadata.Query.EntityMetadataProperties.IsAvailableOffline = "IsAvailableOffline", SDK.Metadata.Query.EntityMetadataProperties.IsChildEntity = "IsChildEntity", SDK.Metadata.Query.EntityMetadataProperties.IsConnectionsEnabled = "IsConnectionsEnabled", SDK.Metadata.Query.EntityMetadataProperties.IsCustomEntity = "IsCustomEntity", SDK.Metadata.Query.EntityMetadataProperties.IsCustomizable = "IsCustomizable", SDK.Metadata.Query.EntityMetadataProperties.IsDocumentManagementEnabled = "IsDocumentManagementEnabled", SDK.Metadata.Query.EntityMetadataProperties.IsDuplicateDetectionEnabled = "IsDuplicateDetectionEnabled", SDK.Metadata.Query.EntityMetadataProperties.IsEnabledForCharts = "IsEnabledForCharts", SDK.Metadata.Query.EntityMetadataProperties.IsImportable = "IsImportable", SDK.Metadata.Query.EntityMetadataProperties.IsIntersect = "IsIntersect", SDK.Metadata.Query.EntityMetadataProperties.IsMailMergeEnabled = "IsMailMergeEnabled", SDK.Metadata.Query.EntityMetadataProperties.IsManaged = "IsManaged", SDK.Metadata.Query.EntityMetadataProperties.IsMappable = "IsMappable", SDK.Metadata.Query.EntityMetadataProperties.IsReadingPaneEnabled = "IsReadingPaneEnabled", SDK.Metadata.Query.EntityMetadataProperties.IsRenameable = "IsRenameable", SDK.Metadata.Query.EntityMetadataProperties.IsValidForAdvancedFind = "IsValidForAdvancedFind", SDK.Metadata.Query.EntityMetadataProperties.IsValidForQueue = "IsValidForQueue", SDK.Metadata.Query.EntityMetadataProperties.IsVisibleInMobile = "IsVisibleInMobile", SDK.Metadata.Query.EntityMetadataProperties.LogicalName = "LogicalName", SDK.Metadata.Query.EntityMetadataProperties.ManyToManyRelationships = "ManyToManyRelationships", SDK.Metadata.Query.EntityMetadataProperties.ManyToOneRelationships = "ManyToOneRelationships", SDK.Metadata.Query.EntityMetadataProperties.MetadataId = "MetadataId", SDK.Metadata.Query.EntityMetadataProperties.ObjectTypeCode = "ObjectTypeCode", SDK.Metadata.Query.EntityMetadataProperties.OneToManyRelationships = "OneToManyRelationships", SDK.Metadata.Query.EntityMetadataProperties.OwnershipType = "OwnershipType", SDK.Metadata.Query.EntityMetadataProperties.PrimaryIdAttribute = "PrimaryIdAttribute", SDK.Metadata.Query.EntityMetadataProperties.PrimaryNameAttribute = "PrimaryNameAttribute", SDK.Metadata.Query.EntityMetadataProperties.Privileges = "Privileges", SDK.Metadata.Query.EntityMetadataProperties.RecurrenceBaseEntityLogicalName = "RecurrenceBaseEntityLogicalName", SDK.Metadata.Query.EntityMetadataProperties.ReportViewName = "ReportViewName", SDK.Metadata.Query.EntityMetadataProperties.SchemaName = "SchemaName", SDK.Metadata.Query.EntityMetadataProperties.__enum = !0, SDK.Metadata.Query.EntityMetadataProperties.__flags = !0, SDK.Metadata.Query.AttributeMetadataProperties.prototype = { AttributeOf: "AttributeOf", AttributeType: "AttributeType", CalculationOf: "CalculationOf", CanBeSecuredForCreate: "CanBeSecuredForCreate", CanBeSecuredForRead: "CanBeSecuredForRead", CanBeSecuredForUpdate: "CanBeSecuredForUpdate", CanModifyAdditionalSettings: "CanModifyAdditionalSettings", ColumnNumber: "ColumnNumber", DefaultFormValue: "DefaultFormValue", DefaultValue: "DefaultValue", DeprecatedVersion: "DeprecatedVersion", Description: "Description", DisplayName: "DisplayName", EntityLogicalName: "EntityLogicalName", Format: "Format", ImeMode: "ImeMode", IsAuditEnabled: "IsAuditEnabled", IsCustomAttribute: "IsCustomAttribute", IsCustomizable: "IsCustomizable", IsManaged: "IsManaged", IsPrimaryId: "IsPrimaryId", IsPrimaryName: "IsPrimaryName", IsRenameable: "IsRenameable", IsSecured: "IsSecured", IsValidForAdvancedFind: "IsValidForAdvancedFind", IsValidForCreate: "IsValidForCreate", IsValidForRead: "IsValidForRead", IsValidForUpdate: "IsValidForUpdate", LinkedAttributeId: "LinkedAttributeId", LogicalName: "LogicalName", MaxLength: "MaxLength", MaxValue: "MaxValue", MetadataId: "MetadataId", MinValue: "MinValue", OptionSet: "OptionSet", Precision: "Precision", PrecisionSource: "PrecisionSource", RequiredLevel: "RequiredLevel", SchemaName: "SchemaName", Targets: "Targets", YomiOf: "YomiOf" }, SDK.Metadata.Query.AttributeMetadataProperties.AttributeOf = "AttributeOf", SDK.Metadata.Query.AttributeMetadataProperties.AttributeType = "AttributeType", SDK.Metadata.Query.AttributeMetadataProperties.CalculationOf = "CalculationOf", SDK.Metadata.Query.AttributeMetadataProperties.CanBeSecuredForCreate = "CanBeSecuredForCreate", SDK.Metadata.Query.AttributeMetadataProperties.CanBeSecuredForRead = "CanBeSecuredForRead", SDK.Metadata.Query.AttributeMetadataProperties.CanBeSecuredForUpdate = "CanBeSecuredForUpdate", SDK.Metadata.Query.AttributeMetadataProperties.CanModifyAdditionalSettings = "CanModifyAdditionalSettings", SDK.Metadata.Query.AttributeMetadataProperties.ColumnNumber = "ColumnNumber", SDK.Metadata.Query.AttributeMetadataProperties.DefaultFormValue = "DefaultFormValue", SDK.Metadata.Query.AttributeMetadataProperties.DefaultValue = "DefaultValue", SDK.Metadata.Query.AttributeMetadataProperties.DeprecatedVersion = "DeprecatedVersion", SDK.Metadata.Query.AttributeMetadataProperties.Description = "Description", SDK.Metadata.Query.AttributeMetadataProperties.DisplayName = "DisplayName", SDK.Metadata.Query.AttributeMetadataProperties.EntityLogicalName = "EntityLogicalName", SDK.Metadata.Query.AttributeMetadataProperties.Format = "Format", SDK.Metadata.Query.AttributeMetadataProperties.ImeMode = "ImeMode", SDK.Metadata.Query.AttributeMetadataProperties.IsAuditEnabled = "IsAuditEnabled", SDK.Metadata.Query.AttributeMetadataProperties.IsCustomAttribute = "IsCustomAttribute", SDK.Metadata.Query.AttributeMetadataProperties.IsCustomizable = "IsCustomizable", SDK.Metadata.Query.AttributeMetadataProperties.IsManaged = "IsManaged", SDK.Metadata.Query.AttributeMetadataProperties.IsPrimaryId = "IsPrimaryId", SDK.Metadata.Query.AttributeMetadataProperties.IsPrimaryName = "IsPrimaryName", SDK.Metadata.Query.AttributeMetadataProperties.IsRenameable = "IsRenameable", SDK.Metadata.Query.AttributeMetadataProperties.IsSecured = "IsSecured", SDK.Metadata.Query.AttributeMetadataProperties.IsValidForAdvancedFind = "IsValidForAdvancedFind", SDK.Metadata.Query.AttributeMetadataProperties.IsValidForCreate = "IsValidForCreate", SDK.Metadata.Query.AttributeMetadataProperties.IsValidForRead = "IsValidForRead", SDK.Metadata.Query.AttributeMetadataProperties.IsValidForUpdate = "IsValidForUpdate", SDK.Metadata.Query.AttributeMetadataProperties.LinkedAttributeId = "LinkedAttributeId", SDK.Metadata.Query.AttributeMetadataProperties.LogicalName = "LogicalName", SDK.Metadata.Query.AttributeMetadataProperties.MaxLength = "MaxLength", SDK.Metadata.Query.AttributeMetadataProperties.MaxValue = "MaxValue", SDK.Metadata.Query.AttributeMetadataProperties.MetadataId = "MetadataId", SDK.Metadata.Query.AttributeMetadataProperties.MinValue = "MinValue", SDK.Metadata.Query.AttributeMetadataProperties.OptionSet = "OptionSet", SDK.Metadata.Query.AttributeMetadataProperties.Precision = "Precision", SDK.Metadata.Query.AttributeMetadataProperties.PrecisionSource = "PrecisionSource", SDK.Metadata.Query.AttributeMetadataProperties.RequiredLevel = "RequiredLevel", SDK.Metadata.Query.AttributeMetadataProperties.SchemaName = "SchemaName", SDK.Metadata.Query.AttributeMetadataProperties.Targets = "Targets", SDK.Metadata.Query.AttributeMetadataProperties.YomiOf = "YomiOf", SDK.Metadata.Query.AttributeMetadataProperties.__enum = !0, SDK.Metadata.Query.AttributeMetadataProperties.__flags = !0, SDK.Metadata.Query.RelationshipMetadataProperties.prototype = { AssociatedMenuConfiguration: "AssociatedMenuConfiguration", CascadeConfiguration: "CascadeConfiguration", Entity1AssociatedMenuConfiguration: "Entity1AssociatedMenuConfiguration", Entity1IntersectAttribute: "Entity1IntersectAttribute", Entity1LogicalName: "Entity1LogicalName", Entity2AssociatedMenuConfiguration: "Entity2AssociatedMenuConfiguration", Entity2IntersectAttribute: "Entity2IntersectAttribute", Entity2LogicalName: "Entity2LogicalName", IntersectEntityName: "IntersectEntityName", IsCustomizable: "IsCustomizable", IsCustomRelationship: "IsCustomRelationship", IsManaged: "IsManaged", IsValidForAdvancedFind: "IsValidForAdvancedFind", MetadataId: "MetadataId", ReferencedAttribute: "ReferencedAttribute", ReferencedEntity: "ReferencedEntity", ReferencingAttribute: "ReferencingAttribute", ReferencingEntity: "ReferencingEntity", RelationshipType: "RelationshipType", SchemaName: "SchemaName", SecurityTypes: "SecurityTypes" }, SDK.Metadata.Query.RelationshipMetadataProperties.AssociatedMenuConfiguration = "AssociatedMenuConfiguration", SDK.Metadata.Query.RelationshipMetadataProperties.CascadeConfiguration = "CascadeConfiguration", SDK.Metadata.Query.RelationshipMetadataProperties.Entity1AssociatedMenuConfiguration = "Entity1AssociatedMenuConfiguration", SDK.Metadata.Query.RelationshipMetadataProperties.Entity1IntersectAttribute = "Entity1IntersectAttribute", SDK.Metadata.Query.RelationshipMetadataProperties.Entity1LogicalName = "Entity1LogicalName", SDK.Metadata.Query.RelationshipMetadataProperties.Entity2AssociatedMenuConfiguration = "Entity2AssociatedMenuConfiguration", SDK.Metadata.Query.RelationshipMetadataProperties.Entity2IntersectAttribute = "Entity2IntersectAttribute", SDK.Metadata.Query.RelationshipMetadataProperties.Entity2LogicalName = "Entity2LogicalName", SDK.Metadata.Query.RelationshipMetadataProperties.IntersectEntityName = "IntersectEntityName", SDK.Metadata.Query.RelationshipMetadataProperties.IsCustomizable = "IsCustomizable", SDK.Metadata.Query.RelationshipMetadataProperties.IsCustomRelationship = "IsCustomRelationship", SDK.Metadata.Query.RelationshipMetadataProperties.IsManaged = "IsManaged", SDK.Metadata.Query.RelationshipMetadataProperties.IsValidForAdvancedFind = "IsValidForAdvancedFind", SDK.Metadata.Query.RelationshipMetadataProperties.MetadataId = "MetadataId", SDK.Metadata.Query.RelationshipMetadataProperties.ReferencedAttribute = "ReferencedAttribute", SDK.Metadata.Query.RelationshipMetadataProperties.ReferencedEntity = "ReferencedEntity", SDK.Metadata.Query.RelationshipMetadataProperties.ReferencingAttribute = "ReferencingAttribute", SDK.Metadata.Query.RelationshipMetadataProperties.ReferencingEntity = "ReferencingEntity", SDK.Metadata.Query.RelationshipMetadataProperties.RelationshipType = "RelationshipType", SDK.Metadata.Query.RelationshipMetadataProperties.SchemaName = "SchemaName", SDK.Metadata.Query.RelationshipMetadataProperties.SecurityTypes = "SecurityTypes", SDK.Metadata.Query.RelationshipMetadataProperties.__enum = !0, SDK.Metadata.Query.RelationshipMetadataProperties.__flags = !0, function () { this.OwnershipType = function () { throw new Error("Constructor not implemented this is a static enum."); }, this.AttributeTypeCode = function () { throw new Error("Constructor not implemented this is a static enum."); }, this.RelationshipType = function () { throw new Error("Constructor not implemented this is a static enum."); }, this.AttributeRequiredLevel = function () { throw new Error("Constructor not implemented this is a static enum."); }, this.DateTimeFormat = function () { throw new Error("Constructor not implemented this is a static enum."); }, this.ImeMode = function () { throw new Error("Constructor not implemented this is a static enum."); }, this.IntegerFormat = function () { throw new Error("Constructor not implemented this is a static enum."); }, this.SecurityTypes = function () { throw new Error("Constructor not implemented this is a static enum."); }, this.StringFormat = function () { throw new Error("Constructor not implemented this is a static enum."); } }.call(SDK.Metadata.Query.ValueEnums), SDK.Metadata.Query.ValueEnums.OwnershipType.prototype = { None: "None", OrganizationOwned: "OrganizationOwned", TeamOwned: "TeamOwned", UserOwned: "UserOwned" }, SDK.Metadata.Query.ValueEnums.OwnershipType.None = "None", SDK.Metadata.Query.ValueEnums.OwnershipType.OrganizationOwned = "OrganizationOwned", SDK.Metadata.Query.ValueEnums.OwnershipType.TeamOwned = "TeamOwned", SDK.Metadata.Query.ValueEnums.OwnershipType.UserOwned = "UserOwned", SDK.Metadata.Query.ValueEnums.OwnershipType.__enum = !0, SDK.Metadata.Query.ValueEnums.OwnershipType.__flags = !0, SDK.Metadata.Query.ValueEnums.AttributeTypeCode.prototype = { BigInt: "BigInt", Boolean: "Boolean", CalendarRules: "CalendarRules", Customer: "Customer", DateTime: "DateTime", Decimal: "Decimal", Double: "Double", EntityName: "EntityName", Integer: "Integer", Lookup: "Lookup", ManagedProperty: "ManagedProperty", Memo: "Memo", Money: "Money", Owner: "Owner", PartyList: "PartyList", Picklist: "Picklist", State: "State", Status: "Status", String: "String", Uniqueidentifier: "Uniqueidentifier", Virtual: "Virtual" }, SDK.Metadata.Query.ValueEnums.AttributeTypeCode.BigInt = "BigInt", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.Boolean = "Boolean", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.CalendarRules = "CalendarRules", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.Customer = "Customer", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.DateTime = "DateTime", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.Decimal = "Decimal", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.Double = "Double", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.EntityName = "EntityName", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.Integer = "Integer", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.Lookup = "Lookup", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.ManagedProperty = "ManagedProperty", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.Memo = "Memo", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.Money = "Money", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.Owner = "Owner", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.PartyList = "PartyList", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.Picklist = "Picklist", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.State = "State", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.Status = "Status", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.String = "String", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.Uniqueidentifier = "Uniqueidentifier", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.Virtual = "Virtual", SDK.Metadata.Query.ValueEnums.AttributeTypeCode.__enum = !0, SDK.Metadata.Query.ValueEnums.AttributeTypeCode.__flags = !0, SDK.Metadata.Query.ValueEnums.RelationshipType.prototype = { Default: "Default", ManyToManyRelationship: "ManyToManyRelationship", OneToManyRelationship: "OneToManyRelationship" }, SDK.Metadata.Query.ValueEnums.RelationshipType.Default = "Default", SDK.Metadata.Query.ValueEnums.RelationshipType.ManyToManyRelationship = "ManyToManyRelationship", SDK.Metadata.Query.ValueEnums.RelationshipType.OneToManyRelationship = "OneToManyRelationship", SDK.Metadata.Query.ValueEnums.OwnershipType.__enum = !0, SDK.Metadata.Query.ValueEnums.OwnershipType.__flags = !0, SDK.Metadata.Query.ValueEnums.AttributeRequiredLevel.prototype = { ApplicationRequired: "ApplicationRequired", None: "None", Recommended: "Recommended", SystemRequired: "SystemRequired" }, SDK.Metadata.Query.ValueEnums.AttributeRequiredLevel.ApplicationRequired = "ApplicationRequired", SDK.Metadata.Query.ValueEnums.AttributeRequiredLevel.None = "None", SDK.Metadata.Query.ValueEnums.AttributeRequiredLevel.Recommended = "Recommended", SDK.Metadata.Query.ValueEnums.AttributeRequiredLevel.SystemRequired = "SystemRequired", SDK.Metadata.Query.ValueEnums.AttributeRequiredLevel.__enum = !0, SDK.Metadata.Query.ValueEnums.AttributeRequiredLevel.__flags = !0, SDK.Metadata.Query.ValueEnums.DateTimeFormat.prototype = { DateAndTime: "DateAndTime", DateOnly: "DateOnly" }, SDK.Metadata.Query.ValueEnums.DateTimeFormat.DateAndTime = "DateAndTime", SDK.Metadata.Query.ValueEnums.DateTimeFormat.DateOnly = "DateOnly", SDK.Metadata.Query.ValueEnums.DateTimeFormat.__enum = !0, SDK.Metadata.Query.ValueEnums.DateTimeFormat.__flags = !0, SDK.Metadata.Query.ValueEnums.ImeMode.prototype = { Active: "Active", Auto: "Auto", Disabled: "Disabled", Inactive: "Inactive" }, SDK.Metadata.Query.ValueEnums.ImeMode.Active = "Active", SDK.Metadata.Query.ValueEnums.ImeMode.Auto = "Auto", SDK.Metadata.Query.ValueEnums.ImeMode.Disabled = "Disabled", SDK.Metadata.Query.ValueEnums.ImeMode.Inactive = "Inactive", SDK.Metadata.Query.ValueEnums.ImeMode.__enum = !0, SDK.Metadata.Query.ValueEnums.ImeMode.__flags = !0, SDK.Metadata.Query.ValueEnums.IntegerFormat.prototype = { Duration: "Duration", Language: "Language", Locale: "Locale", None: "None", TimeZone: "TimeZone" }, SDK.Metadata.Query.ValueEnums.IntegerFormat.Duration = "Duration", SDK.Metadata.Query.ValueEnums.IntegerFormat.Language = "Language", SDK.Metadata.Query.ValueEnums.IntegerFormat.Locale = "Locale", SDK.Metadata.Query.ValueEnums.IntegerFormat.None = "None", SDK.Metadata.Query.ValueEnums.IntegerFormat.TimeZone = "TimeZone", SDK.Metadata.Query.ValueEnums.IntegerFormat.__enum = !0, SDK.Metadata.Query.ValueEnums.IntegerFormat.__flags = !0, SDK.Metadata.Query.ValueEnums.SecurityTypes.prototype = { Append: "Append", Inheritance: "Inheritance", None: "None", ParentChild: "ParentChild", Pointer: "Pointer" }, SDK.Metadata.Query.ValueEnums.SecurityTypes.Append = "Append", SDK.Metadata.Query.ValueEnums.SecurityTypes.Inheritance = "Inheritance", SDK.Metadata.Query.ValueEnums.SecurityTypes.None = "None", SDK.Metadata.Query.ValueEnums.SecurityTypes.ParentChild = "ParentChild", SDK.Metadata.Query.ValueEnums.SecurityTypes.Pointer = "Pointer", SDK.Metadata.Query.ValueEnums.SecurityTypes.__enum = !0, SDK.Metadata.Query.ValueEnums.SecurityTypes.__flags = !0, SDK.Metadata.Query.ValueEnums.StringFormat.prototype = { Email: "Email", PhoneticGuide: "PhoneticGuide", Text: "Text", TextArea: "TextArea", TickerSymbol: "TickerSymbol", Url: "Url", VersionNumber: "VersionNumber" }, SDK.Metadata.Query.ValueEnums.StringFormat.Email = "Email", SDK.Metadata.Query.ValueEnums.StringFormat.PhoneticGuide = "PhoneticGuide", SDK.Metadata.Query.ValueEnums.StringFormat.Text = "Text", SDK.Metadata.Query.ValueEnums.StringFormat.TextArea = "TextArea", SDK.Metadata.Query.ValueEnums.StringFormat.TickerSymbol = "TickerSymbol", SDK.Metadata.Query.ValueEnums.StringFormat.Url = "Url", SDK.Metadata.Query.ValueEnums.StringFormat.VersionNumber = "VersionNumber", SDK.Metadata.Query.ValueEnums.StringFormat.__enum = !0, SDK.Metadata.Query.ValueEnums.StringFormat.__flags = !0;
document.implementation.hasFeature("XPath", "3.0") && (Document.prototype.selectNodes = function (n, t) { var i; t || (t = this); var f = this.createNSResolver(this.documentElement), r = this.evaluate(n, t, f, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null), u = []; for (i = 0; i < r.snapshotLength; i++) u[i] = r.snapshotItem(i); return u }, Document.prototype.selectSingleNode = function (n, t) { t || (t = this); var i = this.selectNodes(n, t); return i.length > 0 ? i[0] : null }, Element.prototype.selectNodes = function (n) { if (this.ownerDocument.selectNodes) return this.ownerDocument.selectNodes(n, this); throw "For XML Elements Only"; }, Element.prototype.selectSingleNode = function (n) { if (this.ownerDocument.selectSingleNode) return this.ownerDocument.selectSingleNode(n, this); throw "For XML Elements Only"; });

function RetrieveSiteMap() {
    // Retrieve sitemap xml
    SDK.REST.retrieveMultipleRecords("SiteMap", "$select=SiteMapXml",
            function (data) {
                if (data[0] != null) {
                    var siteMapXml = data[0].SiteMapXml;

                    if (siteMapXml != null && siteMapXml != "") {
                        var siteMapDoc = null;
                        if (window.ActiveXObject) {
                            siteMapDoc = new ActiveXObject('Msxml2.DOMDocument.6.0');
                            siteMapDoc.loadXML(siteMapXml);
                        } else {
                            var parser = new DOMParser();
                            siteMapDoc = parser.parseFromString(siteMapXml, "text/xml");
                        }
                        BuildNav(siteMapDoc);
                    }

                }
            },
            function (error) {
            }, function () { });
}

function GetSystemSubAreaNames(subArea) {

    var language = GetUserLanguage();

    var subAreaTitle = "";
    if (subArea == "nav_dashboards") {
        subAreaTitle = language["dashboardTitle"];
    }
    else if (subArea == "nav_personalwall") {
        subAreaTitle = language["whatsNewTitle"];
    }
    else if (subArea == "nav_activities") {
        subAreaTitle = language["activitiesTitle"];
    }
    else if (subArea == "nav_queues") {
        subAreaTitle = language["queuesTitle"];
    }
    else if (subArea == "nav_import") {
        subAreaTitle = language["activitiesTitle"];
    }
    else if (subArea == "nav_apptbook") {
        subAreaTitle = language["serviceCalendarTitle"];
    }
    else if (subArea == "nav_businessmanagement") {
        subAreaTitle = language["businessManagementTitle"];
    }
    else if (subArea == "nav_template") {
        subAreaTitle = language["templatesTitle"];
    }
    else if (subArea == "nav_productcatalog") {
        subAreaTitle = language["productCatalogTitle"];
    }
    else if (subArea == "nav_administration") {
        subAreaTitle = language["administrationTitle"];
    }
    else if (subArea == "nav_datamanagement") {
        subAreaTitle = language["dataManagementTitle"];
    }
    else if (subArea == "nav_systemjobs") {
        subAreaTitle = language["systemJobsTitle"];
    }
    else if (subArea == "nav_documentmanagement") {
        subAreaTitle = language["documentManagementTitle"];
    }
    else if (subArea == "nav_audit") {
        subAreaTitle = language["auditingTitle"];
    }
    else if (subArea == "nav_syscust") {
        subAreaTitle = language["customizationsTitle"];
    }
    else if (subArea == "nav_marketplace") {
        subAreaTitle = language["marketplaceTitle"];
    }
    else if (subArea == "nav_social") {
        subAreaTitle = language["emailConfigurationTitle"];
    }
    else if (subArea == "nav_traces") {
        subAreaTitle = language["alertsTitle"];
    }
    else if (subArea == "nav_calendar") {
        subAreaTitle = language["calendarTitle"];
    }
    else if (subArea == "nav_lc_overview") {
        subAreaTitle = language["highlightsTitle"];
    }
    else if (subArea == "nav_lc_customization") {
        subAreaTitle = language["administrationTitle"];
    }
    else if (subArea == "nav_servicemanagement") {
        subAreaTitle = language["serviceManagementTitle"];
    }
    else if (subArea == "Help_Resource_Center") {
        subAreaTitle = language["customerCenterTitle"];
    }
    else if (subArea == "nav_answers") {
        subAreaTitle = language["knowledgeBaseTitle"];
    }
    return subAreaTitle;

}

var userPrivilegesDoc = null;
function RetrieveUserPrivileges() {
    var context = _Context();
    var envelopeXml = '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><request i:type="b:RetrieveUserPrivilegesRequest" xmlns:a="http://schemas.microsoft.com/xrm/2011/Contracts" xmlns:b="http://schemas.microsoft.com/crm/2011/Contracts"><a:Parameters xmlns:c="http://schemas.datacontract.org/2004/07/System.Collections.Generic"><a:KeyValuePairOfstringanyType><c:key>UserId</c:key><c:value i:type="d:guid" xmlns:d="http://schemas.microsoft.com/2003/10/Serialization/">' + context.getUserId() + '</c:value></a:KeyValuePairOfstringanyType></a:Parameters><a:RequestId i:nil="true" /><a:RequestName>RetrieveUserPrivileges</a:RequestName></request></Execute></s:Body></s:Envelope>';
    var req = new XMLHttpRequest();

    req.open("POST", context.getClientUrl() + "/XRMServices/2011/Organization.svc/web", true);
    req.setRequestHeader("Accept", "application/xml, text/xml, */*");
    req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
    req.onreadystatechange = function () {
        //debugger;
        if (this.readyState == 4 /* complete */) {
            if (this.status == 200 || this.status == 204 || this.status == 1223) {

                if (window.ActiveXObject) {
                    userPrivilegesDoc = new ActiveXObject('Msxml2.DOMDocument.6.0');
                    userPrivilegesDoc.loadXML(this.responseText);
                } else {
                    var parser = new DOMParser();
                    userPrivilegesDoc = parser.parseFromString(this.responseText, "text/xml");
                }
                RetrieveSiteMap();
            }
        }
    };
    req.send(envelopeXml);
}

function ValidateUserPrivilegeToEntity(EntityName, subArea) {
    // Prv = prvReadContact
    var prvName;
    if (EntityName == 'activitypointer') {
        prvName = 'prvReadactivity';
    }
    else if (EntityName == 'salesorder') {
        prvName = 'prvReadorder';
    }
    else if (EntityName == 'bulkoperation') {
        if (subArea.substring(0, 2) == "MA") {
            // Read privilege for Activity: enables QuickCampaigns submenu on Marketing
            prvName = "prvReadActivity";
        }
        else {
            prvName = "prvAllowQuickCampaign";
        }
    }
    else if (EntityName == 'queueitem') {
        prvName = 'prvReadqueue';
    }
    else if (EntityName == 'kbarticle') {
        prvName = 'prvReadarticle';
    }
    else if (EntityName == 'opportunityproduct') {
        prvName = 'prvReadopportunity';
    }
    else {
        prvName = "prvRead" + EntityName;
    }

    SDK.REST.retrieveMultipleRecords("Privilege", "$select=PrivilegeId&$filter=Name eq '" + prvName + "'&$top=1",
            function (data) {
                if (data[0] != null) {
                    var privId = data[0].PrivilegeId;

                    if (privId != null && privId != "") {
                        // Check if user has priv

                        var userPrivLookupResult = userPrivilegesDoc.selectSingleNode("//*[local-name() = 'PrivilegeId'][text()='" + privId + "'] ");
                        if (userPrivLookupResult == null) {
                            // No priv found so do somehting

                            parent.$("#nmu" + subArea).css("visibility", "hidden");
                            parent.$("#nmu" + subArea).css("display", "none");

                        }

                    }
                }
            },
            function (error) {
            }, function () {
            });
}
